gpt4 book ai didi

java - 如何通过传递对象类型将json转换为对象

转载 作者:行者123 更新时间:2023-12-01 19:19:31 25 4
gpt4 key购买 nike

 public static Object convertToObject(String json) {
validate("json", json);
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, new TypeReference<Object>(){});
} catch (JsonProcessingException ex) {
throw new RuntimeException("Failed to convert json to object: "+json, ex);
}
}

//Here I'm doing type cast for the returned object
Map<String, ArrayList<Integer>> convertedMap = (Map<String, ArrayList<Integer>>) RestClient.convertToObject(json);

我尝试了上面的代码我正在使用 Jackson,我需要传递带有类型的 json,这样我就可以避免在调用者位置进行类型转换。

有人可以帮我吗?

提前致谢

最佳答案

对象映射器需要第二个参数作为Class类型,因此请尝试传递:

Object.class

如下:

return mapper.readValue(json, Object.class);

关于java - 如何通过传递对象类型将json转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59376278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com