gpt4 book ai didi

使用Gson对泛型进行Java反序列化

转载 作者:搜寻专家 更新时间:2023-11-01 03:27:59 25 4
gpt4 key购买 nike

我正在尝试反序列化某些通用类型。它工作得很好,但我想将这段代码换成一个方法。

Type listType = new TypeToken<TestResult<MyObject>>(){}.getType();
TestResult<MyObject> result = new Gson().fromJson(json, listType);

我该怎么做,证明有关类型的信息?

最佳答案

是的,你可以。有一个解决方法。您只需明确地将“MyObject”的类型和类传递给该方法。

针对您的情况,开发一个具有以下签名和正文的方法。

public <T> Object getGenericDataObjectFromJson(String json, Type t, Class<T> type) {

// Convert Json String to Java object
TestResult<T> obj = gson.fromJson(json, t);

return obj;
}

在哪里

  1. String json = 你的json字符串
  2. 键入 listType = 作为参数传递的 listType 对象
  3. 类类型 = MyObject.class

然后方法调用会变成这样

GsonUtility gs = new GsonUtility();// Your gson utility class
JSONObject jsonObj = "your json string";

// Explicitly identifying the type so as to pass it to the method
// Because The type of a generics can't be determinted during runtime as #CKuk said

Type objectType = new TypeToken<DataObject<objectType>>(){}.getType();

TestResult<MyObject> resultObject= (TestResult<MyObject>) gs.getGenericDataObjectFromJson(jsonObj.toString(), objectType, MyObject.class);

关于使用Gson对泛型进行Java反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8294777/

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