简体   繁体   English

使用Gson进行JSON解析

[英]JSON parsing using Gson

I am trying to parse a JSON object using GSON. 我试图使用GSON解析JSON对象。

My JSON is : 我的JSON是:

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

I have defined my 2 classes like: 我已经定义了我的2个类,如:

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. Gson创建一个TruncatObj子级,但是List<TruncateObjectChild>List<TruncateObjectChild>为空。

What is wrong in what I am doing? 我在做什么有什么问题?

The field objChild in your TruncateObj does not match the name it has in the JSON. TruncateObj中的字段objChild与它在JSON中的名称不匹配。 Rename the field to truncate and try again. 将字段重命名为truncate试。

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. 或者,您可以使用@SerializedName("truncate")注释objChild字段,以告知gson使用JSON中truncate字段的值作为Java对象中objChild字段的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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