Make GSON accept single objects where it expects arrays

后端 未结 4 678
你的背包
你的背包 2020-12-06 06:29

I have bunch of model classes which have fields of type List where X is one of many things (e.g. String, Integer

4条回答
  •  伪装坚强ぢ
    2020-12-06 07:06

    When using the GSON library, you could just check whether or not the following token is an object or an array. This of course requires you to go more fine grained while parsing the XML, but it allows you full control of what do you want to get from it. Sometimes we are not under control of the XML, and it could come handy.

    This is an example to check if the next token is an object or an array, using the JsonReader class to parse the file:

    if (jsonReader.peek() == JsonToken.BEGIN_ARRAY) {
        jsonReader.beginArray()
    } else if (jsonReader.peek() == JsonToken.BEGIN_OBJECT) {
        jsonReader.beginObject()
    }
    

    And at the end of the array / object, you could do the same, but for the end tokens:

    if (jsonReader.peek() == JsonToken.END_ARRAY) {
        jsonReader.endArray()
    } else if (jsonReader.peek() == JsonToken.END_OBJECT) {
        jsonReader.endObject()
    }
    

    This way, you could have identical code (adding an extra check, to verify if you are on an array or on an object) to parse your array of objects, or a single object.

提交回复
热议问题