Gson JSON获取结果 [英] Gson json getting the result
问题描述
我有一个像这样的json字符串:
I have a json string like this:
{
"d": {
"results": [
{
"__metadata": {
"uri": "http://localhost:2000",
"key_fields": "Accountnum",
"rows_affected": 0,
"last_autoinc": 0
},
"Accountnum": "9999999",
"workphone": null,
"name": "Smith",
"address": "33 Main St",
"city": "Anytown",
"state": "FL",
"zip": "33333",
}
]
}
}
,并且我尝试根据此处关于stackoverflow的不同问题对它进行反序列化,但是我做不到. 这是我创建的课程,我只需要一个accountnum和名称.
and I tried to deserialize it according to diffrent questions here on stackoverflow, but I can't get it right. Here is what I did I created a class, I only need the accountnum and name.
public class Result {
@SerializedName("Accountnum")
public String accountnumStr;
@SerializedName("name")
public String nameStr;
}
我有一个带有json myresult的字符串.
I have a string with the json myresult.
Gson gson = new Gson();
Result result = gson.fromJson(myresult,Result.class);
myName.setText(result.nameStr);
我收到一个空字符串. 谢谢
I receive an empty string. Thanks
推荐答案
如果您以类对象的形式可视化JSON,则完全没有问题.想象一下,您的根对象包含类型为"D"的名为"d"的属性.类型"D"包含另一个类型结果"的结果"列表.结果包含上面的属性.这是它的图片:
If you visualize your JSON in terms of class objects then it will be no problem at all. Imagine that your root object contains a property named "d" of type "D". And type "D" contains a list of "results" of another type "Result". The result contains its properties as above. Here's the picture of it:
class RootObj {
D d;
}
class D {
List<Result> results;
}
class Result {
@SerializedName("Accountnum")
public String accountnumStr;
@SerializedName("name")
public String nameStr;
}
要从JSON获取对象,请执行以下操作:
To get the objects from a JSON, you would do the following:
Gson g = new Gson();
RootObj ro = g.fromJson(jsonString, RootObj.class);
这篇关于Gson JSON获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!