如题,测试代码如下:
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不起作用,那么对于这种场景,希望坚持使用泛型处理,可以做到吗?请指正。