要使用 jackson API 将 json 字符串转换为 pojo 可以使用:
String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"mkyong\"}";
User user1 = mapper.readValue(jsonInString, User.class);
这需要创建与 json 字符串结构匹配的 User 类。
使用 json-simple API 可以使用:
JSONObject json = (JSONObject)new JSONParser().parse(jsonInString);
使用json-simple不需要包含与json格式匹配的pojo。 jackson 可以使用类似的方法吗? json-simple 不太冗长,因为不必创建与 json 结构匹配的类。
最佳答案
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)
关于java - json-simple 与 jackson 在没有 obj 类型时解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33800076/