使用gson将json转换为Map时,我们拥有具有所有值String或Boolean的LinkedTreeMap实例…偶数转换为String…
Gson gson = new GsonBuilder().create();
Map<String, Object> result = gson.fromJson(EXAMPLE, new TypeToken<Map<String,Object>>() {}.getType());
我们如何使用相应的原始包装器将json转换为最简单的HashMap?在这种情况下,性能也非常重要…我想创建尽可能少的垃圾并重用解析器…
有办法使用gson吗?或任何其他lib?
请不要建议为每个json创建特殊的java类型…
这里有一个例子
{ // Hashmap (as no ordering or sorting is essential)
"bool": true, // Boolean
"string": "string", // String
"int" : 123, // Long for all non floats are ok but if possible i'd like this to be Integer if it fits, otherwise Long
"long" : 100000000000000, // Long if Integer cant contain the number...
"double" : 123.123435, // all floating point nubmers will just map to Double
"object" : { // another HashMap
...
}
"array" : [ // Array or some collection like ArrayList or LinkedList
...
]
}
目标是尽可能快地将任何json转换为javaMap(如果json的根是数组,则为数组),然后使用一些访问器方法来访问数据……而不是为每个可能的json结构发明java类型……
适用于杰克逊数据库库:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(jsonString, Map.class);
映射中的值将具有相应的类型。此测试通过:
@Test
public void test() throws Exception {
String jsonString = "{\"bool\": true,"
+ "\"str\":\"strv\","
+ "\"long\": 100000000000000}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(jsonString , Map.class);
assertEquals(Long.class, map.get("long").getClass());
assertEquals(Boolean.class, map.get("bool").getClass());
}