Gson等同于Jackson的@JsonInclude(JsonInclude.Include.NON_NULL)。

huangapple go评论86阅读模式
英文:

Gson equivalent to Jackson @JsonInclude(JsonInclude.Include.NON_NULL)

问题

这实际上是对这个问题的跟进 https://stackoverflow.com/questions/64006127/recreate-dto-class-without-field-property-instead-of-having-it-null-using-gson-j?noredirect=1#comment113310166_64006127。我最初发布了这个问题,试图使其在 Gson 中工作,但只能在使用 @JsonInclude(JsonInclude.Include.NON_NULL) 的情况下使用 Jackson 来实现,但是在 Gson 中尚未找到等效的方法,以便我可以将其保留作为项目的库。

尝试在我有 @JsonInclude 注释的地方使用 @Expose(serialise=false, deserialise=false),或者将该字段设置为 null,因为默认情况下 Gson 应该会忽略它,但它似乎并没有这样做。

最后,我尝试完全从中删除 @Expose 注释,以查看 Gson 是否会忽略它,但也没有起作用。

以下是问题的主要部分,以及保留在原始帖子中添加的额外细节。

@Service
public class CategoryQueryServiceImpl implements CategoryQueryService {

@Autowired
private CategoryRepository categoryRepository;

@Autowired
private ReportRepository reportRepository;

ObjectMapper mapper = new ObjectMapper();

@Override
public CategoryQueryDto getCategory(UUID id) throws JsonProcessingException {

    if (categoryRepository.findById(id).isPresent()) {
        Category category = categoryRepository.findById(id).get();

        CategoryQueryDto categoryQueryDto = new CategoryQueryDto(category.getId(), category.getTitle());

          Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
          String converter = gson.toJson(categoryQueryDto);
          categoryQueryDto = gson.fromJson(converter, CategoryQueryDto.class);


        // Jackson
        //String converter = mapper.writeValueAsString(categoryQueryDto);

        //categoryQueryDto = mapper.readValue(converter, CategoryQueryDto.class);


        return categoryQueryDto;


    } else {
        return null;
    }

}

@AllArgsConstructor
@NoArgsConstructor
@Data
public class CategoryQueryDto {

@Expose()
private UUID id;
@Expose()
private String title;

// Jackson
// @JsonInclude(JsonInclude.Include.NON_NULL)
private List<ReportQueryDto> reports = null;

public CategoryQueryDto(UUID id, String title) {
    this.id = id;
    this.title = title;
}

}

如果有其他人有关于如何解决这个问题的想法,请告诉我。非常感谢。

英文:

This is actually a follow up for this question https://stackoverflow.com/questions/64006127/recreate-dto-class-without-field-property-instead-of-having-it-null-using-gson-j?noredirect=1#comment113310166_64006127. I originally posted it trying to make it work with Gson but only able to do it with Jackson using the @JsonInclude(JsonInclude.Include.NON_NULL) but haven't been able to find an equivalent for this with Gson so I can keep that as the library for the project.

Tried using @Expose(serialise=false, deserialise=false) where I had the @JsonInclude annotation or set that field to null as thought Gson by default would ignore that, but it doesn't seem to do it.

Finally, I tried to remove the @Expose annotation completely from to see if Gson would ignore that but not working either.

Pasting it here the main pieces for the issue as well as keeping the extra details added to the original post.

@Service
public class CategoryQueryServiceImpl implements CategoryQueryService {
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private ReportRepository reportRepository;
ObjectMapper mapper = new ObjectMapper();
@Override
public CategoryQueryDto getCategory(UUID id) throws JsonProcessingException {
if (categoryRepository.findById(id).isPresent()) {
Category category = categoryRepository.findById(id).get();
CategoryQueryDto categoryQueryDto = new CategoryQueryDto(category.getId(), category.getTitle());
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String converter = gson.toJson(categoryQueryDto);
categoryQueryDto = gson.fromJson(converter, CategoryQueryDto.class);
// Jackson
//String converter = mapper.writeValueAsString(categoryQueryDto);
//categoryQueryDto = mapper.readValue(converter, CategoryQueryDto.class);
return categoryQueryDto;
} else {
return null;
}
}
@AllArgsConstructor
@NoArgsConstructor
@Data
public class CategoryQueryDto {
@Expose()
private UUID id;
@Expose()
private String title;
// Jackson
// @JsonInclude(JsonInclude.Include.NON_NULL)
private List&lt;ReportQueryDto&gt; reports = null;
public CategoryQueryDto(UUID id, String title) {
this.id = id;
this.title = title;
}
}

If anyone has any other ideas on how to do this please.
Thank you very much.

答案1

得分: 1

不要序列化空字段(这是Gson序列化的默认行为)

Employee employeeObj = new Employee(1, "John", "Smith", null);
                     
Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .create(); 
     
System.out.println(gson.toJson(employeeObj));

输出:

{
  "id": 1,
  "firstName": "John",
  "lastName": "Smith"
}

序列化空字段(使用自定义的Gson序列化,在JSON输出中包含空值)

Employee employeeObj = new Employee(1, "John", "Smith", null);
                     
Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .serializeNulls()
        .create(); 
     
System.out.println(gson.toJson(employeeObj));

输出:

{
  "id": 1,
  "firstName": "John",
  "lastName": "Smith",
  "emailId": null
}
英文:

DO NOT serialize null fields (This is the default behavior of Gson serialization)

Employee employeeObj = new Employee(1, &quot;John&quot;, &quot;Smith&quot;, null);
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create(); 
System.out.println(gson.toJson(employeeObj));

Output:

{
&quot;id&quot;: 1,
&quot;firstName&quot;: &quot;John&quot;,
&quot;lastName&quot;: &quot;Smith&quot;
}

Serialize null fields (Custom Gson serialization with null values included in JSON output)

Employee employeeObj = new Employee(1, &quot;John&quot;, &quot;Smith&quot;, null);
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
.create(); 
System.out.println(gson.toJson(employeeObj));

Output:

{
&quot;id&quot;: 1,
&quot;firstName&quot;: &quot;John&quot;,
&quot;lastName&quot;: &quot;Smith&quot;,
&quot;emailId&quot;: null
}

答案2

得分: 0

似乎Gson的默认行为没有生效,因为Spring Boot使用Jackson作为默认序列化库。通过在application.properties文件中粘贴下面这行代码,我已经解决了这个问题。

spring.mvc.converters.preferred-json-mapper=gson
英文:

It seems the default behaviour for Gson was not taking place as Spring Boot uses Jackson as the default serialisation library. Overwriting this by pasting the below line within the application.properties file has fixed the issue for me.

spring.mvc.converters.preferred-json-mapper=gson

huangapple
  • 本文由 发表于 2020年9月29日 00:20:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64105969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定