Brandon
Brandon

Reputation: 1886

Defining Model for Gson with extra attributes

I'm defining models for Gson serialization/deserialization and I'm trying to figure out the best way given my particular JSON response.

Each API call in my app is of a similar format:

In my model, I really only care about the data. For instance, if user calls /get_buddies, I just want to get a list of all the buddies. But I also 'care' about the status too, right? If the status is 'error' for some reason (user isn't logged in, or something), I want to tell the user that and Toast the message (that's a bad example, as it'd never happen)...

How do I create my model so that I can read status and message, but so that if I package this model as JSON to send, I don't package those up.

My first thought from my research is to have a class called GetBuddiesCall

public class GetBuddiesCall {
    String status;
    String message;
    ArrayList<Buddy> buddies;
}

and then a class Buddy

public class Buddy {
    String username;
    String firstName;
    String lastName;
    // etc.
}

Then, Gson will look at these two models and be able to deserialize accordingly. Then, when attempting to serialize, I only use the Buddy model as the status and message aren't necessary for client -> server communication. Is there a better way than this? I know that there are modifiers you can use like transient, which keeps Gson from looking at that field when packaging up a JSON.

Thanks for any assistance!

Upvotes: 1

Views: 222

Answers (1)

JHH
JHH

Reputation: 9285

Two ways:

  1. Using @Expose annotation explicitly for all fields, you can select if each field should be just serialized, just deserialized or both. Note that this also requires GsonBuilder.excludeFieldsWithoutExposeAnnotation() to be set. https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/annotations/Expose.html

  2. Define a custom exclusion strategy: https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/ExclusionStrategy.html

    In the simplest form such an implementation could hard-code fields to skip; a more advanced but also flexible approach would be to also define your own custom annotation and have the exclusion strategy check for its presence for each field, e.g. it could be something like @ReadOnly or @Exclude(read = true, write = false).

    Note that you can set excursion strategies per serialization and deserialization independently: https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html#addDeserializationExclusionStrategy(com.google.gson.ExclusionStrategy)

If your project is small, using the @Expose annotation is definitely quickest. The back side of it is simply that it somewhat clutters the code.

Upvotes: 1

Related Questions