有人可以提供将
json
反序列化为 TreeMap
的代码吗?Gson
库
这是json
:
{
"сars": [
{
"brand": "audi",
"color": "black"
},
{
"brand": "bmw",
"color": "white"
}
]
}
这是不起作用的代码:
public class ReadGarageTest {
public static void main(String[] args) throws IOException {
readGarage();
}
public static void readGarage() throws IOException {
Path filePath = Paths.get("example.json");
String json = Files.readString(filePath);
Gson gson = new Gson();
Type type = new TypeToken<TreeMap<String, Car>>() {}.getType();
TreeMap<String, Car> garage = gson.fromJson(json, type);
System.out.print(garage.keySet());
}
}
与杰克逊一起,我提出了一些方法:
public static Object convertJsonRequestToObject(HttpServletRequest pRequest, Class<?> pObject) throws JsonParseException, JsonMappingException, IOException {
return new ObjectMapper().readValue(IOUtils.toString(pRequest.getInputStream(), StandardCharsets.UTF_8), pObject);
}
public static Map<String,Object> parseJsonToMap(String json) throws JsonParseException, JsonMappingException, IOException{
return new ObjectMapper().readValue(json, HashMap.class);
}
public static Map<String,Object> parseObjectToMap(Object object){
return (Map<String, Object>) new ObjectMapper().convertValue(object, Map.class);
}
//inverse
public static Object parseMapToObject(Map<?, ?> pMap, Class<?> pClass){
return new ObjectMapper().convertValue(pMap, pClass);
}