如何使用 Gson 将 JSON 转换为 ArrayList?
How can i convert JSON to ArrayList using Gson?
嗨,我是 android 的新手,我想使用 Gson 将我的 JSON 对象转换为 ArrayList 为此,我编写了以下代码,但这不起作用。
请帮助我。
如何将我的 JSON 对象转换为 ArrayList?
JSON 回应:-
{
"header" : {
"alerts" : [
{
"AlertID" : "2",
"TSExpires" : null,
"Target" : "1",
"Text" : "woot",
"Type" : "1"
},
{
"AlertID" : "3",
"TSExpires" : null,
"Target" : "1",
"Text" : "woot",
"Type" : "1"
}
],
"session" : "0bc8d0835f93ac3ebbf11560b2c5be9a"
},
"result" : "4be26bc400d3c"
}
我的代码:-
private void handleEscortRelations(String JSONresponse) {
if (JSONresponse != null) {
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<TerritoryBean>>() {
}.getType();
ArrayList<String> escortRelationList = new ArrayList<>();
escortRelationList = new Gson().fromJson(JSONresponse, type);
}
}
模型对象:-
public class TerritoryBean {
private String AlertID;
private String Text;
public String getAlertID() {
return AlertID;
}
public void setAlertID(int AlertID) {
AlertID = AlertID;
}
public String getText() {
return Text;
}
public void setText(String Text) {
Text = Text;
}
}
您应该在 json 结构上对齐您的 类:
public class Response {
private Header header;
private String result;
}
public class Header {
private List<TerritoryBean> alerts;
private String session;
}
public class TerritoryBean {
private String AlertID;
private String TSExpires;
private String Target;
private String Text;
private String Type;
}
从那里你应该能够将你的 json 反序列化为 Response 对象。
嗨,我是 android 的新手,我想使用 Gson 将我的 JSON 对象转换为 ArrayList 为此,我编写了以下代码,但这不起作用。
请帮助我。
如何将我的 JSON 对象转换为 ArrayList?
JSON 回应:-
{
"header" : {
"alerts" : [
{
"AlertID" : "2",
"TSExpires" : null,
"Target" : "1",
"Text" : "woot",
"Type" : "1"
},
{
"AlertID" : "3",
"TSExpires" : null,
"Target" : "1",
"Text" : "woot",
"Type" : "1"
}
],
"session" : "0bc8d0835f93ac3ebbf11560b2c5be9a"
},
"result" : "4be26bc400d3c"
}
我的代码:-
private void handleEscortRelations(String JSONresponse) {
if (JSONresponse != null) {
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<TerritoryBean>>() {
}.getType();
ArrayList<String> escortRelationList = new ArrayList<>();
escortRelationList = new Gson().fromJson(JSONresponse, type);
}
}
模型对象:-
public class TerritoryBean {
private String AlertID;
private String Text;
public String getAlertID() {
return AlertID;
}
public void setAlertID(int AlertID) {
AlertID = AlertID;
}
public String getText() {
return Text;
}
public void setText(String Text) {
Text = Text;
}
}
您应该在 json 结构上对齐您的 类:
public class Response {
private Header header;
private String result;
}
public class Header {
private List<TerritoryBean> alerts;
private String session;
}
public class TerritoryBean {
private String AlertID;
private String TSExpires;
private String Target;
private String Text;
private String Type;
}
从那里你应该能够将你的 json 反序列化为 Response 对象。