2016-12-29 50 views
0

我在將Json轉換爲Java對象時遇到了問題。 我的「jsonText」字段具有json作爲我想要放在字符串中的值。我的自定義類具有以下結構。如何在Java中使用ObjectMapper將JSON值視爲字符串對象?

Class Custom{ 
    @JsonProperty(value = "field1") 
    private String field1; 
    @JsonProperty(value = "jsonText") 
    private String jsonText; 
} 

下面是我的代碼:

ObjectMapper mapper = new ObjectMapper(); 

JsonNode node = mapper.readTree(inputString); 
String nodeTree = node.path("jsonText").toString(); 
List<PatientMeasure> measuresList =mapper.readValue(nodeTree, 
          TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, CustomClass.class)); 

JSON來轉換是:

"field1" : "000000000E",     
    "jsonText" : { 
     "rank" : "17", 
     "status" : "", 
     "id" : 0 
    } 

異常有:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token 
at [Source: [email protected]; line: 1, column: 108] (through reference chain: com.Custom["jsonText"]) 

回答

1

你可以試試這個:

JSONArray ar= new JSONArray(result); 
JSONObject jsonObj= ar.getJSONObject(0); 
String strname = jsonObj.getString("NeededString"); 
+1

我需要直接映射它String對象上。是否有任何Json屬性 – usman

+0

您不能直接將值獲取到字符串中,並且您可以使用帶有字符串標題名稱的JSON對象來獲取該值,如上所述。 –

1

您可以使用自定義解串器是這樣的:

public class AnythingToString extends JsonDeserializer<String> { 

    @Override 
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { 
     TreeNode tree = jp.getCodec().readTree(jp); 
     return tree.toString(); 
    } 
} 

然後註釋你的領域使用該解串器:

class Custom{ 
    @JsonProperty(value = "field1") 
    private String field1; 
    @JsonProperty(value = "jsonText") 
    @JsonDeserialize(using = AnythingToString.class) 
    private String jsonText; 
} 
相關問題