Jason Miesionczek
Jason Miesionczek

Reputation: 14448

Prevent certain fields from being serialized

In the Play framework i have a few models that have fields which are object references to other models. When i use renderJSON, i don't want those object references to be included. Currently for my needs i create a separate view model class which contains the fields i want, and in the controller i create instances of this view class as needed. Ideally i would like to be able to use the model class itself without having to write the view class.

Is there a way to annotate a field so that it will not be serialized when using renderJSON?

Upvotes: 5

Views: 3358

Answers (4)

raddevus
raddevus

Reputation: 9077

Not sure why no one has written the most direct solution to this answer so I will do it here:

Simply mark the fields you do not want serialized via Gson as transient.

Here's an example:

public class Animal
{
        private String name = "dog";
        transient private int port = 80;
        private String species = "canine";
        transient private String password = "NoOneShouldSeeThis";
}

None of the items which are marked transient will be serialized. When deserialized they will be set to their default (class default) values.

Resulting JSON will look like the following:

{"name":"dog","species":"canine"}

For more information on transient you can see the SO Why does Java have transient fields?

Upvotes: 0

Brad Mace
Brad Mace

Reputation: 27886

Using FlexJSON with play is another option, explained in this article: http://www.lunatech-research.com/archives/2011/04/20/play-framework-better-json-serialization-flexjson

Upvotes: 2

Johann Sonntagbauer
Johann Sonntagbauer

Reputation: 1294

because play uses Gson for its Json serialization you can try the following:

public static void test()  
{  
    Object foo = new SomeObject("testData");  
    Gson gson = new GsonBuilder()
        .excludeFieldsWithModifiers(Modifier.TRANSIENT)  
        .create();
    renderJSON(gson.toJson(foo));  
}

now each field marked as transient will not be serialized. There is also another (better) way. You can use the com.google.gson.annotations.Expose annotation to mark each field you want to serialize.

public static void test()  
{  
    Object foo = new SomeObject("testData");  
    Gson gson = new GsonBuilder()
        .excludeFieldsWithoutExposeAnnotation()  
        .create();
    renderJSON(gson.toJson(foo));  
}

Upvotes: 11

Kyle Wild
Kyle Wild

Reputation: 8915

I would override renderJSON to check a the field name against a member array of serialization exclusions.

Upvotes: -1

Related Questions