Reputation: 435
I want to serialize a java object to JSON with Google's GSON library. It works fine except when a ArrayList occurs. GSON isn't able to handle the generic type of the ArrayList. @Yavor Georgiev described a solution with the registerSerializer(...) method, but this method doesn't exist in the new releases.
gson.registerSerializer(ArrayList.class, new CollectionSerializer<Object>());
http://hashtagfail.com/post/44606137082/mobile-services-android-serialization-gson
In my case the ArrayList is nested in a class three layers under the object, which is passed to toJSON(...)
.
Does anyone know how to solve this problem?
The structure is like this:
public class Data() {
@Expose
privat int number = 8;
@Expose
private Foo foo = new Foo();
}
public class Foo() {
@Expose
private Bar bar = new Bar();
}
import java.awt.Point;
public class Bar() {
@Expose
ArrayList<Point> list = new ArrayList()<>;
}
Upvotes: 2
Views: 456
Reputation: 3932
Have you tried registering an Adapter.
new GsonBuilder().registerTypeAdapter(Object.class, new JsonSerializer<Object>() {
@Override
public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src);
}
})
Upvotes: 1