根據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