Android 反序列化多级JSON
我对JSON的概念是完全陌生的,并且很难弄清楚如何使用Gson反序列化多级JSON语句 这就是我试图反序列化的内容:{stat:ok,pkey:{id:1234567890}} 首先,我尝试使用hashmap:Android 反序列化多级JSON,android,json,gson,Android,Json,Gson,我对JSON的概念是完全陌生的,并且很难弄清楚如何使用Gson反序列化多级JSON语句 这就是我试图反序列化的内容:{stat:ok,pkey:{id:1234567890}} 首先,我尝试使用hashmap: HashMap<String, Object> results = gson.fromJson(response, HashMap.class); 我能在网上找到的唯一例子是反序列化简单的一级JSON,这看起来很简单。我似乎无法理解这一点。使用JSONObject可以轻松地
HashMap<String, Object> results = gson.fromJson(response, HashMap.class);
我能在网上找到的唯一例子是反序列化简单的一级JSON,这看起来很简单。我似乎无法理解这一点。使用JSONObject可以轻松地反序列化多级JSON 这是您的示例中的Log ok和1234567890
String json = "{\"stat\":\"ok\",\"pkey\":{\"id\":\"1234567890\"}}";
try {
JSONObject jsonObj = new JSONObject(json);
Log.i("chauster", jsonObj.getString("stat"));
Log.i("chauster", jsonObj.getJSONObject("pkey").getString("id"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是gson的代码,您需要自定义您的类
public class Custom {
private String stat;
private IdClass pkey;
public String getStat() {
return stat;
}
public IdClass getPkey() {
return pkey;
}
public Custom(String _stat, IdClass _pkey) {
stat = _stat;
pkey = _pkey;
}
public class IdClass {
private String id;
public String getId() {
return id;
}
public IdClass(String _id){
id = _id;
}
}
}
String json = "{\"stat\":\"ok\",\"pkey\":{\"id\":\"1234567890\"}}";
Gson gson = new Gson();
Custom custom = gson.fromJson(json, Custom.class);
System.out.println(custom.getStat());
System.out.println(custom.getPkey().getId());
不幸的是,我必须使用Gson来实现这一点。我为Gson添加了可以登录ok和1234567890的代码。但是您需要为json字符串创建自定义类
public class Custom {
private String stat;
private IdClass pkey;
public String getStat() {
return stat;
}
public IdClass getPkey() {
return pkey;
}
public Custom(String _stat, IdClass _pkey) {
stat = _stat;
pkey = _pkey;
}
public class IdClass {
private String id;
public String getId() {
return id;
}
public IdClass(String _id){
id = _id;
}
}
}
String json = "{\"stat\":\"ok\",\"pkey\":{\"id\":\"1234567890\"}}";
Gson gson = new Gson();
Custom custom = gson.fromJson(json, Custom.class);
System.out.println(custom.getStat());
System.out.println(custom.getPkey().getId());