JSON parsing using Gson

戏子无情 提交于 2019-12-11 04:46:40

问题


I am trying to parse a JSON object using GSON.

My JSON is :

{ "truncate": [
            {
                "lower": 20,
                "upper": 40,
                "delimiter": " ",
                "scope": ["$title"]
            },
            {
                "lower": 30,
                "upper": 65,
                "delimiter": " "
            }
        ] }

I have defined my 2 classes like:

public class TruncateObj {

    private List<TruncateObjectChild> objChild;

    // getter and setter
}

and

public class TruncateObjectChild {

    private int lower;

    private int upper;

    private String delimiter;

    private List<String> scope;

// getters and setters
}

My Parsing statement is

 Gson gson = new Gson();   
 TruncateObj truncation = gson.fromJson(template, TruncateObj.class);

For some reason this is not working. Gson creates a TruncatObj child, but the List<TruncateObjectChild> within the TruncateObj is null.

What is wrong in what I am doing?


回答1:


The field objChild in your TruncateObj does not match the name it has in the JSON. Rename the field to truncate and try again.

Alternatively, you could annotate the objChild field with an @SerializedName("truncate") to tell gson to use the value from the truncate field in the JSON as the value for the objChild field in your Java object.



来源:https://stackoverflow.com/questions/8207274/json-parsing-using-gson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!