json(包含很少的对象)到java上的TreeMap

问题描述 投票:0回答:1

有人可以提供将

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());
    }
}
java json collections deserialization treemap
1个回答
1
投票

与杰克逊一起,我提出了一些方法:

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.