简体   繁体   English

如何从具有不同字段的同一类创建两个 json 文件

[英]How to create the two json file from same class with different fields

In my application i need to create the two json file from same object(object contain input + output fields) Json file - 1: This json file should contain only input fields.在我的应用程序中,我需要从同一个对象(对象包含输入 + 输出字段)创建两个 json 文件 Json 文件 - 1:这个 json 文件应该只包含输入字段。 Json file - 2: This json file should contain few input fields and all output fields. Json 文件 - 2:此 json 文件应包含很少的输入字段和所有输出字段。

Let me explain with small example让我用一个小例子来解释

below is the class from which i wants to generate the two json file下面是我想从中生成两个json文件的类

Class AreaDTO {
 String id;
 String name;
 String streetName;
 Street output;
}
json file 1     |   json file 2
{               |   {
  id            |       id
  name          |       name
  streetName    |       output
}              |    }

To creating object to json file currently i am using jackson, How to achieve my above requiremnet with jackson or is there any other way to achieve this?要为 json 文件创建对象,我目前正在使用 jackson,如何使用 jackson 实现我的上述要求,或者还有其他方法可以实现吗?

You can use @JsonInclude(Include.NON_NULL) annotation at the class level.您可以在类级别使用 @JsonInclude(Include.NON_NULL) 注释。 Then set the fields to null which you don't need.然后将不需要的字段设置为 null。 Then Jackson will ignore the fields which are null.然后杰克逊将忽略为空的字段。

Please check https://mkyong.com/java/jackson-how-to-ignore-null-fields/请检查https://mkyong.com/java/jackson-how-to-ignore-null-fields/

One more option is to use a custom JSON filter.另一种选择是使用自定义 JSON 过滤器。 Use Jackson to only serialize a field if it meets a specific, custom criteria.使用 Jackson 仅在满足特定的自定义条件时序列化字段。

Please check https://www.baeldung.com/jackson-serialize-field-custom-criteria请检查https://www.baeldung.com/jackson-serialize-field-custom-criteria

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

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