使GsonRequest接受空列表或空数组

时间:2014-03-03 09:19:48

标签: android json gson

我有一个从服务器中提取的Json数据。此数据包含多个对象和数组。

第一个模型如下:

{
  "results": [
    {
      "id": "17",
      "name": "Accessories",
      "child": [
        {
          "id": "371",
          "name": "Belt"
        },
        {
          "id": "55",
          "name": "Derp"
        },
        ...
      ]
    }
  ]
}

但是,某些results数组没有child数组。相反,它有一个空值的String。

{
  "results": [
    {
      "id": "19",
      "name": "Stuff",
      "child": ""
    }
  ]
}

执行代码时,它返回以下行:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING

这就是模型的样子:

public class CategoryModel {
    @SerializedName("id")
    private String category_id;
    private String name;
    private ArrayList<CategoryChildModel> child;

    ...
}

这就是我实现GsonRequest(使用Volley作为背景asynctask)的方式:

private void loadCategory() {
    mRequestQueue = Volley.newRequestQueue(getActivity());

    String url = Constants.CATEGORIES_LIST;

    GsonRequest<CategoryContainer> myReq = new GsonRequest<CategoryContainer>(
            Request.Method.GET, url, CategoryContainer.class,
            createMyReqSuccessListener(), createMyReqErrorListener());

    mRequestQueue.add(myReq);
}

那么,谁知道如何让null对象通过GsonRequest?

2 个答案:

答案 0 :(得分:5)

实际上你的json响应应该返回一个空数组,而不是一个null的情况下的字符串。但是,如果您没有更改服务器响应的选项,那么您可以尝试编写自定义的json反序列化器:

class ChildDeserializer implements JsonDeserializer<ChildHolder> {
    @Override
    public ChildHolder deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String currentValueOfChild = json.toString();
        Log.d("ChildDeserializer", "ChildDeserializer: child=" + currentValueOfChild);

        ChildHolder childHolder = null;
        if (json instanceof JsonArray) {
            Log.d("ChildDeserializer", "ChildDeserializer: We have an array for 'child'");

            Type listType = new TypeToken<List<Child>>() {}.getType();

            JsonArray jsonArray= json.getAsJsonArray();

            childHolder = new ChildHolder();
            childHolder.childList = context.deserialize(jsonArray, listType);
        }

        return childHolder;
    }
}

您的响应java模型应如下所示:

class Response {
    List<Result> results;
}

class Result {
    private String id, name;
    private ChildHolder child;
}

class ChildHolder {
    private List<Child> childList;
}

class Child {
    private String id, name;
}

在将json解析为java模型时应用反序列化器:

String jsonTest1 = "{\"results\":[{\"id\":\"17\",\"name\":\"Accessories\",\"child\":[{\"id\":\"371\",\"name\":\"Belt\"},{\"id\":\"55\",\"name\":\"Derp\"}]}]}";
String jsonTest2 = "{\"results\":[{\"id\":\"19\",\"name\":\"Stuff\",\"child\":\"\"}]}";

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(ChildHolder.class, new ChildDeserializer());

Gson gson = gsonBuilder.create();
Response response1 = gson.fromJson(jsonTest1, Response.class);
Response response2 = gson.fromJson(jsonTest2, Response.class);

另请read this link了解更多信息。

答案 1 :(得分:1)

编写自定义序列化程序的另一个选择是简单地将空字符串转换为JSON中的空数组。然后你的班级可以保持原样:

class ChildDeserializer implements JsonDeserializer<CategoryModel>
{
    @Override
    public ChildHolder deserialize(JsonElement json, Type typeOfT, 
                                   JsonDeserializationContext context) 
                                       throws JsonParseException {

        JsonObject obj = json.getAsObject();
        JsonElement e = obj.get("child");
        if (e.isJsonPrimitive()) // it's a String
        {
            obj.remove("child");
            obj.add("child", new JsonArray());
        }

        return new Gson().fromJson(obj, CategoryModel.class);
    }
}