【问题标题】:How to treat JSON Value as String Object in Java using ObjectMapper?如何使用 ObjectMapper 将 JSON 值视为 Java 中的字符串对象?
【发布时间】:2016-12-30 18:46:32
【问题描述】:

将 Json 转换为 Java 对象时遇到问题。 我的“jsonText”字段有 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: java.io.StringReader@3362f02f; line: 1, column: 108] (through reference chain: com.Custom["jsonText"])

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

    你可以试试这个:

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

    【讨论】:

    • 我需要将它直接映射到 String 对象上。是否有任何 Json 属性
    • 您不能直接将值转换为字符串,您可以使用上面给出的字符串标题名称的 JSON 对象获取值....
    【解决方案2】:

    您可以像这样使用自定义反序列化器:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2017-01-24
      • 2016-01-02
      • 1970-01-01
      相关资源
      最近更新 更多