Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...