我已经解决了我的问题,我稍后会介绍它,但我不喜欢这就是为什么我会问。有条件地序列化收集字段的最佳做法?
我使用最新的球衣和杰克逊图书馆。我有一个实体的休息服务,到目前为止,我有2个get方法:getById和getList,都使用jackson返回json。实体使用OneToMany关系引用它自己,因此它是一组实体。对于getList我不希望该字段被序列化,而getById我希望它被序列化,但以我自己的方式。
我的解决办法是:
有关的GetList我使用视图中的场 在实体bean我用我的JsonView类FirstLevelOfCollection:
@JsonView(JacksonViews.FirstLevelOfCollection.class)
在休息服务的GetList方法,我用对象作为视图过滤器,所有不@JsonView所有领域将包括:
ObjectMapper mapper = new ObjectMapper();
resultString = mapper.writerWithView(Object.class).writeValueAsString(resultObject);
对于getById我使用自定义的序列化
ObjectMapper mapper = new ObjectMapper();
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null, null, null));
testModule.addSerializer(Set.class, new EndEventCodesSerializer(Set.class));
mapper.registerModule(testModule);
resultString = mapper.writeValueAsString(resultObject);
我不能使用@JsonIgnore insted视图,因为然后自定义序列化也不会看到它。它的作品,但它似乎很奇怪和丑陋,尤其是排除这样的领域,我也想实现,但我不知道如何使用排除(getList行为)默认为所有未来的请求。我可以有更好的解决方案吗?
考虑只使用传输对象。试图将您的DB jpa实体推入JSON,而看起来DRY最终会导致大量工作,混乱和潜在的安全问题。 – 2014-11-23 13:29:56
@Adam Gent你的意思是把JsonIgnore放在实体bean的Set字段中(用于getList rest方法),并为该Set字段(getById rest方法)使用getter编写一个实体包装器? – MaxNevermind 2014-11-23 18:29:09