I need to serialize an object like this:
class A {
int a = 1;
String b = "hello";
boolean isDog = false;
}
into JSON array like this:
[1,"hello",false]
I know one (wrong) way to do this: create an untyped Collection out of object’s fields and then Gson it:
class A {
// ...
Collection forGson() {
ArrayList col = new ArrayList();
col.add(a);
col.add(b);
col.add(c);
return col;
}
}
new Gson().toJson(new A().forGson());
But it produces a lot of warnings because of untyped collections usage. So is there any way to serialize objects into an array of arbitrary types without getting any warnings?
This is literally “You’re doing it wrong”. You don’t have an array of random things, you have an (
A) object. It has nothing in common with the JSON you want to produce.That being said, if you really wanted to do this, you supply your own Serializer / Deserializer to
Gson:You’d create a
JsonDeserializerthat did the reverse, creating aAobject from the supplied JSON array.See: https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization for more info.
Then using
GsonBuilderyou’d tellGsonto use them: