我在使用GsonBuilder注册多个typeAdapter时遇到了问题.似乎只有一个会启动,它永远不会考虑第二个.如果我自己每个人做它似乎工作正常.但我需要他们与两者合作,似乎我做错了什么.我目前正在使用GSON v2.2.4.
Zip对象简单形式:
public class Zip {
private String zipCode;
private String city;
private String state;
public Zip(){}
}
Run Code Online (Sandbox Code Playgroud)
ZipSerializer:
public class ZipSerializer implements JsonSerializer<Zip>{
@Override
public JsonElement serialize(Zip obj, Type type, JsonSerializationContext jsc) {
Gson gson = new Gson();
JsonObject jObj = (JsonObject)gson.toJsonTree(obj);
jObj.remove("state");
return jObj;
}
}
Run Code Online (Sandbox Code Playgroud)
JsonResponse对象简单形式:
public class JsonResponse {
private String jsonrpc = "2.0";
private Object result = null;
private String id = null;
public JsonResponse(){}
}
Run Code Online (Sandbox Code Playgroud)
JsonResponseSerializer:
public class JsonResponseSerializer implements JsonSerializer<JsonResponse> {
@Override …Run Code Online (Sandbox Code Playgroud) gson是一个很棒的图书馆 - 它运作良好.有时我有自定义要求,可以制作和注册TypeAdapters和TypeAdaptorFactories - 这也很有效.
然而令我困惑的是,如何委托回json序列化...大多数时候我需要这个用于集合,但为了说明这一点 - 假设我有一个对类,gson显然会愉快地序列化,但由于某种原因我需要自己的自定义序列化程序.好吧......如果我的配对是
public class Pair
{
public final Object First;
public final Object Second;
public Pair( Object first, Object second) {this.first = first; this.second = second};
}
Run Code Online (Sandbox Code Playgroud)
如果我为此编写了一个类型适配器 - 您希望 write函数看起来像:
public void write( JsonWriter out, Pair pair )
{
out.beginObject();
out.name( "first");
out.value( pair.first ); // can't do this
out.name( "second");
out.value( pair.second); // or this
out.endObject();
}
Run Code Online (Sandbox Code Playgroud)
所以你可以看到问题 - 我不知道第一个和第二个的类型,也不知道它们是如何序列化的.我可以使用gson.toJson来序列化第一个和第二个 - 但是如果我将它们作为字符串添加到编写器中,它们将被转义.有一个gson.tojson函数,它接受一个值和一个编写器 - 但它也需要一个typetoken - 我没有.我得到的印象是,我打算从某个地方安装另一个类型的适配器 - 但是当我只有一个对象列表时......我从哪里得到它?我只是获得对象的适配器?
我有点困惑?当然这是最常见的用例?大多数自定义序列化程序将用于T或T树之类的奇怪列表,并且你真的不知道列表中的内容,除了它继承自T …
也许我跑错了方向,但我有一个我想阅读的元素列表。
我有一个抽象基类,我们称之为Person:
public abstract class Person {
public int id;
public String name;
}
Run Code Online (Sandbox Code Playgroud)
现在我有两种可能的实现:
public class Hunter implements Person {
public int skill;
// and some more stuff
}
public class Zombie implements Person {
public int uglyness;
// and some more stuff
}
Run Code Online (Sandbox Code Playgroud)
现在我有这个示例 JSON:
[
{"id":1, "type":"zombie", "name":"Ugly Tom", "uglyness":42},
{"id":2, "type":"hunter", "name":"Shoot in leg Joe", "skill":0}
]
Run Code Online (Sandbox Code Playgroud)
我怎样才能读这个 JSON 为List<Person>?
我玩了一段时间TypeAdapterFactory并尝试使用一个名为的类,CustomizedTypeAdapterFactory因为我的真实结构比上面有趣的例子要复杂一些。
我最后说我想通过这个调用委托序列化:
return gson.getDelegateAdapter(this, resultType);
Run Code Online (Sandbox Code Playgroud)
但是,我不知道如何在运行时创建TypeToken<T>此调用所需的内容。有任何想法吗?