Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Jason Miesionczek Avatar asked Jan 19 '11 19:01

Jason Miesionczek


1 Answers

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));  
}
like image 118
Johann Sonntagbauer Avatar answered Oct 27 '22 23:10

Johann Sonntagbauer