This is easy enough using a Java object like this:
public class GsonTest {
private List<DataItem> data;
private String label;
public GsonTest() {} // for Gson
public GsonTest(List<DataItem> data, String label) {
this.data = data;
this.label = label;
}
// ...
}
public class DataItem {
private int val1;
private int val2;
private String text;
public DataItem() {} // for Gson
public DataItem(int val1, int val2, String text) {
this.val1 = val1;
this.val2 = val2;
this.text = text;
}
// ...
}
Since your JSON format uses an array rather than an object for each data item (an object would make more sense based on your sample) you need to add a custom handler for serializing and deserializing DataItem
s to and from JSON arrays.
public class DataItemConverter implements JsonDeserializer<DataItem>,
JsonSerializer<DataItem> {
public DataItem deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonArray array = json.getAsJsonArray();
int val1 = array.get(0).getAsInt();
int val2 = array.get(1).getAsInt();
String text = array.get(2).getAsString();
return new DataItem(val1, val2, text);
}
public JsonElement serialize(DataItem src, Type typeOfSrc,
JsonSerializationContext context) {
JsonArray array = new JsonArray();
array.add(new JsonPrimitive(src.val1));
array.add(new JsonPrimitive(src.val2));
array.add(new JsonPrimitive(src.text));
return array;
}
}
Then you just need to register this converter when you create your Gson
instance and you're good to go! Since our DataItem
converter handles deserialization as well, you'll be able to deserialize the generated JSON as a List<GsonTest>
as well.
public static void testSerialization() {
List<DataItem> data = new ArrayList<DataItem>();
data.add(new DataItem(1, 1, "Text"));
data.add(new DataItem(2, 2, "Text"));
data.add(new DataItem(3, 0, "Text"));
data.add(new DataItem(5, 2, "Text"));
GsonTest test = new GsonTest(data, "First Series");
List<GsonTest> list = new ArrayList<GsonTest>();
list.add(test);
Gson gson = new GsonBuilder()
.registerTypeAdapter(DataItem.class, new DataItemConverter())
.create();
System.out.println(gson.toJson(list));
}