最近,我遇到了Gson反序列化问题。这是我的目标:
class Foo{
public List<Donation> donations;
class Donation{
// SerializedName here.
}
}
这是我的json:
{
"donations": [] // sometimes, this array is empty.
}
// this is none empty one.
{
"donations": [
{
"doner_id": 4,
"name": "abc",
"donate": "103"
}
]
}
使用上述对象解析此JSON时,我总是收到错误:Expected a com.google.gson.JsonObject but was com.google.gson.JsonArray
。如果上面的donations
不是空的,那么一切都很顺利。我该怎么做才能解决它?
答案 0 :(得分:0)
在这里,我编译了你的json,它适用于空的和非空的捐赠,检查它是否是你正在寻找的。 p>
String json = "{\n" +
"\"donations\": [\n" +
" {\n" +
" \"doner_id\": 4,\n" +
" \"name\": \"abc\",\n" +
" \"donate\": \"103\"\n" +
" }\n" +
" ]\n" +
"}";
JsonParser jsonParser = new JsonParser();
JsonObject object = jsonParser.parse(json).getAsJsonObject();
Gson gson = new Gson();
SampleModel sampleModels1 = gson.fromJson(object, SampleModel.class);
assertNotNull(sampleModels1);
<强> SampleModel.java 强>
public class SampleModel {
@SerializedName("donations")
@Expose
private List<Donations> mDonationsList;
public List<Donations> getDonationsList() {
return mDonationsList;
}
public void setDonationsList(final List<Donations> donationsList) {
mDonationsList = donationsList;
}
public class Donations {
@SerializedName("doner_id")
@Expose
private String doner_id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("donate")
@Expose
private String donate;
public String getDoner_id() {
return doner_id;
}
public void setDoner_id(final String doner_id) {
this.doner_id = doner_id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDonate() {
return donate;
}
public void setDonate(final String donate) {
this.donate = donate;
}
}
}
答案 1 :(得分:0)
如果它是json数组,请检查一下:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
...
Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);