制作GsonRequest接受空单或空数组 [英] Making GsonRequest to accept empty list or null array

查看:128
本文介绍了制作GsonRequest接受空单或空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON数据从服务器拉出。该数据包含多个对象和数组。

I have a Json data to be pulled from a server. This data contains several objects and arrays.

第一个模型如下:

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

然而,一些结果数组没有孩子阵列。相反,它有一个空值的String。

However, some of the results array doesn't have child array. Instead, it have a String with an empty value.

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

在执行code,它返回这一行:

When the code is executed, it returns this line:

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(其中用排球为背景的AsyncTask):

And this is how I implement the GsonRequest (which using Volley as background 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);
}

因此​​,任何人知道如何使空对象通过GsonRequest?

So, anyone knows how to make null object pass through GsonRequest?

推荐答案

其实你的JSON响应应该返回一个空数组不是空的情况下的字符串。但是,如果你没有一个选项来改变服务器的响应,那么你可以尝试编写自定义的JSON解串器:

Actually your json response should return an empty array not a string for null cases. But if you don't have an option to change server's response then you may try to write a custom json deserializer:

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模型应如下:

Your response java model should look like below:

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模型:

Apply deserializer while parsing json to java model:

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);

另外请阅读更​​多相关信息,链接

这篇关于制作GsonRequest接受空单或空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆