Empty json object instead of null, when no data -> how to deserialize with gson

霸气de小男生 提交于 2019-12-11 02:59:46

问题


I am trying to parse json data with Google's gson library. But the json data doesn't behave well.

It does look like this when everything is alright:

{
    "parent": {
        "child_one": "some String",
        "child_two": "4711",
        ...
    }
}

child_one should be parsed as String, child_two as int. But sometimes one of the children has no values what results in an empty object instead of null, like this:

{
    "parent": {
        "child_one": "some String",
        "child_two": {},
        ...
    }
}

I have no access to alter the json feed, so I have to deal with it during deserialization. But I am lost here. If I just let it parse the 2nd case gives me a JsonSyntaxException.

I thought about using a custom JsonDeserializer. Do there something like inspect every element if it is a JsonObject and if it is, check if the entrySet.isEmpty(). If yes, remove that element. But I have no idea how to accomplish the iterating...


回答1:


Can't you just replace {} with NULL before passing it to the GSON?




回答2:


Make your TypeAdapter<String>'s read method like this:

public String read(JsonReader reader) throws IOException {
    boolean nextNull = false;
    while (reader.peek() == JsonToken.BEGIN_ARRAY || reader.peek() == JsonToken.END_ARRAY) {
        reader.skipValue();
        nextNull = true;
    }
    return nextNull ? null : reader.nextString();
}

Explain: when next token is [ or ], just skip it and return null.

If you replace all [] to null use String#replaceAll directly, some real string may be replaced as well, This may cause some other bugs.



来源:https://stackoverflow.com/questions/18750908/empty-json-object-instead-of-null-when-no-data-how-to-deserialize-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!