简体   繁体   中英

gson.fromJson doesn't load the class

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM