【问题标题】:json-simple versus jackson for parsing json when do not have obj typejson-simple 与 jackson 在没有 obj 类型时解析 json
【发布时间】:2015-11-19 09:39:24
【问题描述】:

使用jackson API将json字符串转换为pojo可以使用:

String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"mkyong\"}";
User user1 = mapper.readValue(jsonInString, User.class);

这需要创建匹配json字符串结构的用户类。

使用 json-simple API 可以改用:

JSONObject json = (JSONObject)new JSONParser().parse(jsonInString);

使用 json-simple 不需要包含匹配 json 格式的 pojo。可以在杰克逊中使用类似的吗? json-simple 不那么冗长,因为不必创建匹配 json 结构的类。

【问题讨论】:

    标签: java json jackson json-simple


    【解决方案1】:

    Jackson 可以将一个 json String 反序列化为一个通用的 Map:

    Map<String, Object> m  = new ObjectMapper().readValue(jsonInString, Map.class);
    for (Map.Entry<String, Object> entry : m.entrySet()) {
        System.out.println(entry.getKey() + " -> " + entry.getValue() + "(" + entry.getValue().getClass().getName() + ")");
    }
    

    输出:

    age -> 33(java.lang.Integer)
    messages -> [msg 1, msg 2](java.util.ArrayList)
    name -> mkyong(java.lang.String)
    

    【讨论】:

      【解决方案2】:

      你可以使用类似的API

      JsonNode node = mapper.readTree(jsonInString);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多