Howto deserialize field that is passed either as a

2020-01-29 21:41发布

问题:

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

回答1:

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.



回答2:

you could make your both sources emitting data to you in similar structure. For example both of them sending list of Objects. if one is sending one object you need to update that one to send you a list of one object, this way you would be able to manage both cases.



标签: java gson