Q:

Howto deserialize field that is passed either as a single Object or as a list of Objects with GSON?

I have successfully used GSON to convert a JSON to a single Object and to convert JSON to a list of objects. My problem is that there are 2 sources emitting data to me. One is only sending one object and the other is sending a list of Objects.
Single object from 1st source:
{
    id : '1',
    title: 'sample title',
    ....
}

List of objects from 2nd source:
[
    {
        id : '1',
        title: 'sample title',
        ....
    },
    {
        id : '2',
        title: 'sample title',
        ....
    },
    ...
]

The class being used for deserializing:
 public class Post {

      private String id;
      private String title;

      /* getters & setters */
 }

Below is working for my 1st case:
Post postData = gson.fromJson(jsonObj.toString(), Post.class);

And this is working for my 2nd case:
Post[] postDatas = gson.fromJson(jsonObj.toString(), Post[].class);

Is there a way to manage both cases? Or should I look into the string and add [] when it is not available
Thanks

A:

How about creating a custom deserializer that checks if the json is an array and if not creates an array having the single object in it, like:
public class PostArrayOrSingleDeserializer implements JsonDeserializer<Post[]> {

    private static final Gson gson = new Gson();

    public Post[] deserialize(JsonElement json, Type typeOfT, 
                JsonDeserializationContext ctx) {
        try {
            return gson.fromJson(json.getAsJsonArray(), typeOfT);
        } catch (Exception e) {
            return new Post[] { gson.fromJson(json, Post.class) };
        }
    }
}

and adding it to your Gson:
Post[] postDatas = new GsonBuilder().setPrettyPrinting()
    .registerTypeAdapter(Post[].class, new PostArrayOrSingleDeserializer())
    .create()
    .fromJson(jsonObj.toString(), Post[].class);

So as a result you should always have an array of Post with one or more items.

