The format of my JSON is :
{"abc": [{
"field_1": "string_1",
"value": 0.304
},
{
"field_1": "string_2",
"value": 0.193
}]}
"abc" is variable, "field_1" and "value" are field names. I want a class in Java which stores this JSON in some format for example:
String t; // should store "abc"
List<myClass> myClassObject; // myClass should contain "field_1" and "value"
myClass.java
String field_1; // should store "string_1" and "string_2"
Double value; // should store 0.304 and 0.193
I want the class myClass.java because in future I may want to add more metadata in JSON response. This is complex object mapping, but I am not able to figure out what should my class be looking like in order to store the JSON response.
For root object do not create new POJO
just use Map
. Example could look like below:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder().create();
Type mapType = new TypeToken<Map<String, List<Item>>>() {
}.getType();
Map<String, List<Item>> map = gson.fromJson(new FileReader(jsonFile), mapType);
Map.Entry<String, List<Item>> first = map.entrySet().stream().findFirst().get();
Items items = new Items(first.getKey(), first.getValue());
System.out.println(items);
}
}
class Items {
private final String key;
private final List<Item> items;
public Items(String key, List<Item> items) {
this.key = key;
this.items = items;
}
public String getKey() {
return key;
}
public List<Item> getItems() {
return items;
}
@Override
public String toString() {
return "Items{" +
"key='" + key + '\'' +
", items=" + items +
'}';
}
}
class Item {
@SerializedName("field_1")
private String field;
private Double value;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
@Override
public String toString() {
return "Item{" +
"field='" + field + '\'' +
", value=" + value +
'}';
}
}
Above code prints:
Items{key='abc', items=[Item{field='string_1', value=0.304}, Item{field='string_2', value=0.193}]}