使用gson将Json转换为Android中的对象 [英] Convert Json to an object in Android with gson
本文介绍了使用gson将Json转换为Android中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含大量条目的JSON数组,并且想要使用gson将每个检查反序列化为一个对象。我的问题是为它找到适当的对象结构。
I have a JSON array with a lot of entries and want to deserialize each check into a single object with gson. My problem is to find the proper object structure for it.
Gson gson = new Gson();
Type collectionType = new TypeToken<List<Client>>(){}.getType();
List<Client> clients = gson.fromJson(response, collectionType);
JSON
[
{
"client": "client1",
"check": {
"handle": true,
"standalone": false,
"interval": 60,
"refresh": 3600,
"dependencies": [
"keepalive"
],
"command": "xxx",
"occurrences": 1,
"subscribers": [
"xxx"
],
"aggregate": false,
"subdue": {
"at": "handler",
"begin": "6PM ICT",
"end": "9AM ICT"
},
"name": "xxx",
"issued": 1437922960,
"executed": 1437922960,
"duration": 0.148,
"output": "xxx",
"status": 0
}
},
{
"client": "client1",
"check": {
"thresholds": {
"warning": 120,
"critical": 180
},
"handler": "keepalive",
"name": "keepalive",
"issued": 1437922959,
"executed": 1437922959,
"output": "Keepalive sent from client 13 seconds ago",
"status": 0
}
}, ....
]
我尝试了下面的对象,但它没有起作用,它只是获取 String client
,但没有任何Check类。 p>
I tried the object below but it didnt work, it just gets String client
but nothing from the Check class.
public class Check {
public Boolean handle;
public Boolean standaloone;
public int interval;
public int refresh;
public String[] dependencies;
public String commmand;
public int occurrences;
public String[] subscribers;
public Boolean aggregate;
public String[] subdue;
public String name;
public int issued;
public int executed;
public float duration;
public String output;
public int status;
}
public class Client {
public String client;
public Check check;
}
推荐答案
您需要设置注释像这样使用GSON
You need to set the annotation like this to use GSON
public class Client {
@SerializedName("client")
public String client;
@SerializedName("check")
public Check check;
}
这篇关于使用gson将Json转换为Android中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文