使用Google GSON解析JSON:直接从子对象读取值 [英] Parsing JSON using Google GSON: reading values directly from child objects

查看:336
本文介绍了使用Google GSON解析JSON:直接从子对象读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Google的Gson解析以下JSON时遇到问题:

I'm having trouble parsing the following JSON with Google's Gson:

{"Name":
    {"object1":   
       {"field1":"17",
        "field2":"360",
        "field3":"19",
        "field4":"sun",
        "field5":"rain"
       }
    }
}

我已经尝试了以下方法来获取field1的值,但它不起作用

I have tried the following to get the value of field1 but it doesn't work

@SerializedName("Name/object1/field1")
public int fieldOne;

我做错了什么?

What am I doing wrong?

推荐答案

你的对象必须保存你的json指令的层次结构。对于你的例子,它会是这样的:

Your objects have to conserve the hierarchy of your json instructions. For your example, it would be something like this:

public class Object {

    @SerializedName("field1")
    public String fieldOne;

    @SerializedName("field2")
    public String fieldTwo;

    @SerializedName("field3")
    public String fieldThree;

    @SerializedName("field4")
    public String fieldFour;
}

public class Name {

    @SerializedName("object1")
    public Object obj;
}

public class GsonObj {

    @SerializedName("Name")
    public Name name;
}

使用以下调用:

Using the following call:

String json = "{\"Name\":{" +
            "\"object1\":{" +
            "\"field1\":\"17\",\"field2\":\"360\",\"field3\":\"19\",\"field4\":\"sun\",\"field5\":\"rain\"}}}";

Gson gson = new Gson();
GsonObj jsonResult = gson.fromJson(json, GsonObj.class);
Log.d("test", "field one: "+jsonResult.name.obj.fieldOne);
Log.d("test", "field two: "+jsonResult.name.obj.fieldTwo);
Log.d("test", "field three: "+jsonResult.name.obj.fieldThree);
Log.d("test", "field four: "+jsonResult.name.obj.fieldFour);

这篇关于使用Google GSON解析JSON:直接从子对象读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆