如何在android中将字符串反序列化为对象

时间:2018-04-05 11:04:40

标签: android arrays json gson

如何在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"
}]

2 个答案:

答案 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