简体   繁体   English

使用Gson库解析Json

[英]Parsing Json Using the Gson Library

Hello Im having trouble figuring out how to create an object using the Gson Library in Java. 您好,我在弄清楚如何使用Java中的Gson库创建对象时遇到了麻烦。 I followed some guides online Link To One Here where they said one has to create each part of the Json structure as classes which I did, but I still get a value of null when the object is created. 我遵循了一些在线指南, 在这里链接到人 ,他们说必须将Json结构的每个部分都作为类进行创建,但是创建对象时我仍然会得到null值。

Nodes nodes = gson.fromJson(obj.get("Nodes"), Nodes.class);

nodes gives me a null value. 节点给我一个空值。

If anyone can help point me out what Im missing or if I created my classes wrong that would be of great help. 如果有人可以帮助我指出我所缺少的内容,或者如果我创建了错误的课程,那将有很大的帮助。

Here is the JSON structure which I want to parse and create an object from: 这是我要解析并从中创建对象的JSON结构:

{
"nodes":[
{
"node":{
"image_thumb":"/sites/all/themes/imsa/images/headlines-thumb.png",
"body_image":" <p>Test</p>\n ",
"title":"Test",
"link":"<a href=\"/articles/test\">view</a>",
"updated":"2013-11-12 11:52",
"body":"<p>Test</p>",
"type":"Article"
}
},
{
"node":{
"image_thumb":"/sites/all/themes/imsa/images/headlines-thumb.png",
"body_image":" <p>test</p>\n ",
"title":"Test Event",
"link":"<a href=\"/articles/test-event\">view</a>",
"updated":"2013-11-08 17:56",
"body":"<p>test</p>",
"type":"Article"
}
},
{
"node":{
"image_thumb":"/sites/all/themes/imsa/images/headlines-thumb.png",
"body_image":" <p>Atricle with no image</p>\n ",
"title":"No Image",
"link":"<a href=\"/articles/no-image\">view</a>",
"updated":"2013-11-01 16:39",
"body":"<p>Atricle with no image</p>",
"type":"Article"
}
},
{
"node":{
"image_thumb":"/sites/default/files/styles/square_thumbnail/public/field/image/test_cars_1.jpg",
"image_medium":"/sites/default/files/styles/media_gallery_thumbnail/public/field/image/test_cars_1.jpg",
"body_image":" <p style=\"text-align: justify; font-size: 11px; line-height: 14px; margin-bottom: 14px; font-family: Arial, Helvetica, sans;\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur dapibus massa vitae mauris elementum dignissim. Etiam ut cursus nulla, at accumsan lacus. Vivamus semper massa ut lorem pulvinar, et porta magna commodo. Quisque tempus ligula eget nisi condimentum lobortis. Praesent in tincidunt massa. Fusce eleifend interdum justo a malesuada. Pellentesque eget condimentum mi, sed congue enim.</p>\n<p style=\"text-align: justify; font-size: 11px; line-height: 14px; margin-bottom: 14px; font-family: Arial, Helvetica, sans;\">Nam ornare pretium volutpat. Sed vitae dolor odio. Cras eleifend tellus at ultrices vehicula. Aenean luctus auctor hendrerit. Nullam egestas at lectus sed scelerisque. Aenean nec sagittis tellus. Aenean nec nibh non erat pellentesque hendrerit id sed quam. Phasellus id dapibus metus. Nunc ultricies enim vitae aliquet semper. Fusce eu mollis elit.</p>\n ",
"title":"Testing it Up",
"subtitle":"As we do",
"link":"<a href=\"/articles/testing-it\">view</a>",
"updated":"2013-10-31 13:31",
"body":"<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur dapibus massa vitae mauris elementum dignissim. Etiam ut cursus nulla, at accumsan lacus. Vivamus semper massa ut lorem pulvinar, et porta magna commodo. Quisque tempus ligula eget nisi condimentum lobortis. Praesent in tincidunt massa. Fusce eleifend interdum justo a malesuada. Pellentesque eget condimentum mi, sed congue enim.</p><p>Nam ornare pretium volutpat. Sed vitae dolor odio. Cras eleifend tellus at ultrices vehicula. Aenean luctus auctor hendrerit. Nullam egestas at lectus sed scelerisque. Aenean nec sagittis tellus. Aenean nec nibh non erat pellentesque hendrerit id sed quam. Phasellus id dapibus metus. Nunc ultricies enim vitae aliquet semper. Fusce eu mollis elit.</p>",
"type":"Article"
}
}
]
}

Here is a class I created which makes an http request to return Json data, and also try using the Gson library here to create an object based on the returned Json structure. 这是我创建的类,该类发出http请求以返回Json数据,并且还尝试在此处使用Gson库基于返回的Json结构创建对象。

private class NewsAsyncTask extends AsyncTask<Void, Void, Void> {

@Override
protected Void doInBackground(Void... params) {
    String url = "http://imsa.com/series/united-sportscar/news.json/";
    HttpGet getRequest = new HttpGet(url);

    try{
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse getResponse = httpClient.execute(getRequest);
        final int statusCode = getResponse.getStatusLine().getStatusCode();

        if(statusCode != HttpStatus.SC_OK) {
            Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
        }

        HttpEntity getResponseEntity = getResponse.getEntity();
        InputStream httpResponseStream = getResponseEntity.getContent();
        InputStreamReader inputStreamReader = new InputStreamReader(httpResponseStream);

        JsonParser parser = new JsonParser();
        JsonObject obj = parser.parse(inputStreamReader).getAsJsonObject();


        Gson gson = new Gson();
        Nodes nodes = gson.fromJson(obj.get("Nodes"), Nodes.class);
        System.out.println(nodes.getNews());
    }
    catch (IOException e) {
        getRequest.abort();
        Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
    }

    return null;
}

The following are all the classes I used that make up the Json structure I want to parse: 以下是我用来构成要解析的Json结构的所有类:

Nodes Class - 节点类-

public class Nodes implements Serializable {

    @SerializedName("nodes")
    private final ArrayList<News> news;

    public Nodes(final ArrayList<News> news) {
        this.news = news;
    }

    public Nodes(final Nodes nodesToCopy) {
        this.news = nodesToCopy.getNews();
    }

    public ArrayList<News> getNews() {
        return news;
    }

    @Override
    public String toString() {
        return "Nodes{" +
                "news=" + news +
                '}';
    }
}

News class - 新闻类-

public class News {

    @SerializedName("node")
    ArrayList<NewsItem> news;

    public News(ArrayList<NewsItem> news) {
        this.news = news;
    }

    public ArrayList<NewsItem> getNews() {
        return news;
    }

    @Override
    public String toString() {
        return "News{" +
                "news=" + news +
                '}';
    }
}

NewsItem Class - NewsItem类-

public class NewsItem implements Serializable {

    @SerializedName("image_thumb")
    private final String imageThumb;

    @SerializedName("image_medium")
    private final String imageMedium;

    @SerializedName("body_image")
    private final String bodyImage;

    @SerializedName("title")
    private final String title;

    @SerializedName("link")
    private final String link;

    @SerializedName("updated")
    private final Date updated;

    @SerializedName("body")
    private final Text body;

    @SerializedName("type")
    private final String type;

    public NewsItem(String imageThumb, String imageMedium, String bodyImage, String title, String link, Date updated, Text body, String type) {
        this.imageThumb = imageThumb;
        this.imageMedium = imageMedium;
        this.bodyImage = bodyImage;
        this.title = title;
        this.link = link;
        this.updated = updated;
        this.body = body;
        this.type = type;
    }

    public NewsItem(final NewsItem newsItemToCopy) {
        this.imageThumb = newsItemToCopy.getImageThumb();
        this.imageMedium = newsItemToCopy.getImageMedium();
        this.bodyImage = newsItemToCopy.getBodyImage();
        this.title = newsItemToCopy.getTitle();
        this.link = newsItemToCopy.getLink();
        this.updated = newsItemToCopy.getUpdated();
        this.body = newsItemToCopy.getBody();
        this.type = newsItemToCopy.getType();
    }

    public String getImageThumb() {

        return imageThumb;
    }

    public String getImageMedium() { return imageMedium; }

    public String getBodyImage() {
        return bodyImage;
    }

    public String getTitle() {
        return title;
    }

    public String getLink() {
        return link;
    }

    public Date getUpdated() {
        return updated;
    }

    public Text getBody() {
        return body;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "NewsItem{" +
                "imageThumb='" + imageThumb + '\'' +
                ", imageMedium='" + imageMedium + '\'' +
                ", bodyImage='" + bodyImage + '\'' +
                ", title='" + title + '\'' +
                ", link='" + link + '\'' +
                ", updated=" + updated +
                ", body=" + body +
                ", type='" + type + '\'' +
                '}';
    }
}

There are a lot of things wrong here, but they are relatively easy to fix. 这里有很多错误,但是相对容易解决。

First 第一

JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(inputStreamReader).getAsJsonObject();

obj now contains your full JSON. obj现在包含完整的JSON。 So when you do 所以当你这样做

obj.get("Nodes")

you are getting the array object called nodes inside this whole JSON. 您将在整个JSON中获取称为nodes的数组对象。 But your Nodes class requires it. 但是您的Nodes类需要它。 So Gson won't find anything and will return null . 因此, Gson将找不到任何东西,并将返回null You need to give obj directly to the fromJson call. 您需要将obj直接提供给fromJson调用。

Second, each node element is a JSON object 其次,每个node元素都是一个JSON对象

"node":{
"image_thumb":"/sites/all/themes/imsa/images/headlines-thumb.png",
"body_image":" <p>Test</p>\n ",
"title":"Test",
"link":"<a href=\"/articles/test\">view</a>",
"updated":"2013-11-12 11:52",
"body":"<p>Test</p>",
"type":"Article"
}

not a JSON array. 不是JSON数组。 Therefore this 所以这个

@SerializedName("node")
ArrayList<NewsItem> news;

is wrong. 是错的。 An ArrayList assumes an array structure, not a single element. ArrayList假定为数组结构,而不是单个元素。 Change that (and the mutators/accessors) to 将其(以及更改器/访问器)更改为

@SerializedName("node")
NewsItem news;

Finally, you haven't set a Date format so Gson won't know how to deserialize 最后,您尚未设置Date格式,因此Gson将不知道如何反序列化

"2013-11-12 11:52"

into a Date object. 转换为Date对象。 You can set your own Date format and get a properly configured Gson object like so 您可以设置自己的Date格式,并获得正确配置的Gson对象,如下所示

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();

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

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