开发者

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 vie开发者_如何学Gow class.

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


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));  
}


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


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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜