根据this tutorial您可以使用JsonSerializer。
注意:在下面的示例中,我已将您的类CollectionImpl重命名。
public class CollectionImpl implements Collection<String> {
private final List<String> _wrappedList = new LinkedList<>();
private String _otherField = "asdf";
// ...
// Note: I've created the class as subclass of CollectionImpl in order to access the
// private fields without implementing a getter (as you maybe want to keep
// your fields completely private)
public static class CollectionImplJsonSerializer implements JsonSerializer<CollectionImpl> {
@Override
public JsonElement serialize(CollectionImpl src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonColl = new JsonObject();
JsonArray array = new JsonArray();
for (String s: src._wrappedList) {
array.add(s);
}
jsonColl.add("_wrappedList", array);
jsonColl.addProperty("_otherField", src._otherField);
return jsonColl;
}
}
}
然后,你可以这样做:
CollectionImpl ci = new CollectionImpl();
GsonBuilder builder = new GsonBuilder();
CollectionImpl.CollectionImplJsonSerializer serializer = new CollectionImpl.CollectionImplJsonSerializer();
builder.registerTypeAdapter(CollectionImpl.class, serializer);
Gson gson = builder.create();
String json = gson.toJson(ci);
我发现CollectionTypeAdapterFactory负责创建一个创建JSON数组的类型适配器,而ReflectiveTypeAdapterFactory将创建导致我的目标的类型适配器。我知道委托给其他类型的适配器,但我如何从ReflectiveTypeAdapterFactory获取类型适配器的有效实例? – efzwo