简体   繁体   English

自定义序列化和反序列化以创建JSON

[英]Custom serialize and deserialize to create JSON

I have a class with 2 values: val1 and val2. 我有一个带有2个值的类:val1和val2。 I am sending val1 to register (create) API and val2 is auto filled by API itself. 我正在发送val1来注册(创建)API,并且val2由API本身自动填充。 I do not want to send val2 while calling create API and that API is not designed for handling unwanted values. 我不想在调用create API时发送val2,并且该API并非旨在处理不需要的值。

In short I want to ignore val2 while I call create API but I want it while I call get API. 简而言之,我想在调用create API时忽略val2,但在调用get API时希望它。

The code that I have right now creates JSON including both the values assigning null to val2. 我现在拥有的代码将创建JSON,其中包括将val2分配为null的两个值。 This causes that API to throw an exception. 这将导致该API引发异常。

Is there any easy way of doing it (java /groovy)? 有没有简单的方法可以做到这一点(java / groovy)?

Is there any easy way of doing it (java /groovy)? 有没有简单的方法可以做到这一点(java / groovy)?

Not 100% sure I'm understanding your need. 并非100%肯定我了解您的需求。 I believe it depends on what json de/serializer you are using. 我相信这取决于您使用的是json de / serializer。 For example, using Jackson we do: 例如,使用杰克逊,我们可以:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeName("account")
public class Account {

I believe this allows us to load in objects with a ton of extra json fields into objects without corresponding java fields. 我相信这可以让我们将具有大量额外json字段的对象加载到没有相应Java字段的对象中。 To quote from the javadocs : 引用javadocs

Property that defines whether it is ok to just ignore any unrecognized properties during deserialization. 定义可以在反序列化期间忽略任何无法识别的属性的属性。 If true, all properties that are unrecognized -- that is, there are no setters or creators that accept them -- are ignored without warnings (although handlers for unknown properties, if any, will still be called) without exception. 如果为true,则所有无法识别的属性(即没有设置器或创建者接受它们)都将在没有警告的情况下被忽略(尽管仍会调用未知属性的处理程序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM