防止某些字段被序列化 [英] Prevent certain fields from being serialized

查看:355
本文介绍了防止某些字段被序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Play框架中,我有一些模型,这些模型的字段是对其他模型的对象引用.当我使用renderJSON时,我不希望包含那些对象引用.目前,根据我的需要,我创建了一个单独的视图模型类,其中包含我想要的字段,并在控制器中根据需要创建了该视图类的实例.理想情况下,我希望能够使用模型类本身而不必编写视图类.

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.

是否有一种方法可以对字段进行注释,以便在使用renderJSON时不会将其序列化?

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

推荐答案

由于游戏使用Gson进行Json序列化,因此您可以尝试以下操作:

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

现在,每个标记为瞬态的字段都不会被序列化.还有另一种(更好)的方法.您可以使用com.google.gson.annotations.Expose批注标记要序列化的每个字段.

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

这篇关于防止某些字段被序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆