如何在android下面反序列化字符串。我试过下面的
String json= ls.get(j).getCwc();
Example example = new Gson().fromJson(json,Example.class);
的Json
[{
"company":"gjjzh",
"AvgSal":"hjsj"
},
{
"company":"hjd",
"AvgSal":"hjd"
},
{
"company":"hm",
"AvgSal":"lk"
},
{
"company":"er",
"AvgSal":"io"
},
{
"company":"uo",
"AvgSal":"tr"
}]
答案 0 :(得分:0)
String json= ls.get(j).getCwc();
Type type = new TypeToken<List<Example>>(){}.getType();
List<Example> example = new Gson().fromJson(json,type);
其中Example
是
public class Example {
@SerializedName("company")
@Expose
private String company;
@SerializedName("AvgSal")
@Expose
private String avgSal;
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getAvgSal() {
return avgSal;
}
public void setAvgSal(String avgSal) {
this.avgSal = avgSal;
}
}
答案 1 :(得分:0)
您需要为对象创建一个模型类。
Example.java
public class Example{
String company = "";
String AvgSal = "";
}
然后您需要编写如下代码,将JSONArray
字符串转换为List<Model>
。
String json= ls.get(j).getCwc();
Type modelListType = new TypeToken<ArrayList<Example>>(){}.getType();
ArrayList<Example> modelList = new Gson().fromJson(json, modelListType);
这会将JSONArray
转换为ArrayList
。