如题,测试代码如下:
public static void main(String[] args) {
Foo x = test("{\"X\": \"x\", \"y\": \"y\"}");
}
@ToString
@Getter
@Setter
static class Foo {
private String x;
private String y;
}
// test1
private static <RESULT> RESULT test(String text) {
// return new Gson().fromJson(text, new TypeToken<RESULT>() {}.getType())
return JSONObject.parseObject(
text,
new TypeReference<RESULT>() {}.getType()
);
}
// test2
private static <RESULT> RESULT test(String text, RESULT result) {
// return new Gson().fromJson(text, new TypeToken<RESULT>() {}.getType())
return JSONObject.parseObject(
text,
new TypeReference<RESULT>() {}.getType()
);
}
我想使用 test 方法进行json到RESULT的转换,但是存在问题,调用这个方法的时候会报错,将Fastjson替换成Gson也会:
class com.alibaba.fastjson.JSONObject cannot be cast to class com.xx.xx.Xx
(com.alibaba.fastjson2.JSONObject and com.xx.xx.Xx are in unnamed module of loader 'app')
产生的原因我是知道的,但是不清楚为什么TypeReference不起作用,那么对于这种场景,希望坚持使用泛型处理,可以做到吗?请指正。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.