2016-12-29 19 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; 
} 
相关问题