0

I try to apply gson.fromJson on the next json:

{
    "1a": {"param1": "text",
        "param2": "text1",
        "param3": [0],
        "param4": "text2",
        "param": "text3"},


    "1b": {"param1": "text",
        "param2": "text1",
        "param3": [0],
        "param4": "text2",
        "param5": "text3"},
//and so on 
}

So I create the next classes:

public class listItems {

private List<ItemCode> itemList;

public List<ItemCode> getItemList() {
    return itemList;
}

public void setItemList(List<ItemCode> itemList) {
    this.itemList= itemList;
}

and then I create the next classes:

public class ItemCode{

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public Item getItem() {
        return item;
    }
    public void setItem(Item item) {
        this.item= item;
    }
    private String code;
    private Item item;
}

and then I create the class Item with the next field with getters and setters:

private String param1;
private String param2;
private String[] param3;
private String param4;
private String param5;

and then I call the method gson.fromJson(text, listItems.class)

and it returns null. Where is my problem, and how I can do it?

Or Smith
  • 3,556
  • 13
  • 42
  • 69

1 Answers1

1

You can easily deserialize your JSON to Map<String, Item>. See below example:

Gson gson = new GsonBuilder().create();
Type type = new TypeToken<Map<String, Item>>(){}.getType();
Map<String, Item> result = gson.fromJson(new FileReader(new File("/x/data.json")), type);
System.out.println(result);

After deserializing you can convert above Map to any POJOs you want. If you want to hide deserialization logic you can write custom deserializer for listItems class.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146