【问题标题】:show null attributes json response spring data rest?显示空属性json响应弹簧数据休息?
【发布时间】:2018-12-27 12:16:52
【问题描述】:

想象一下我有一个这样的实体。

public class Person{
  Long Id,
  String name,
  String city,
  Long age

  //getters, setters, constructor
}

当我创建存储库并使用 GET 请求输出城市条目时,以下是我的 json 响应。

{
  "name": "jon",
  "age": 34
}

但我想要这个。

{
  "name": "jon",
  "city": null,
  "age": 34
}

即显示空属性。

什么是最简单的解决方法?

【问题讨论】:

  • 这很奇怪。无论如何,您应该能够通过正确设置 serializationInclusion 属性来配置 ObjectMapper

标签: java json spring rest spring-data-rest


【解决方案1】:

确保您的ObjectMapper没有以下配置:

mapper.setSerializationInclusion(Include.NON_NULL);

如果有,请将其删除或更改为 Include.ALWAYS


同时检查您的application.properties。如果您使用的是 Spring Boot 1.3,则序列化包含是通过 spring.jackson.serialization-inclusion 属性配置的。

Jackson 2.7 和 Spring Boot 1.4 使用名为 spring.jackson.default-property-inclusion 的属性。

确保此类属性的值为non_null


或者,如下注释您的类:

@JsonInclude(Include.ALWAYS)
public class Person {
    ...
}

【讨论】:

    【解决方案2】:

    我认为您应该检查 json 注释 JsonInclude.Include 并将其设置为 ALWAYS : https://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonInclude.Include.html

    【讨论】:

      猜你喜欢
      • 2018-07-13
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      相关资源
      最近更新 更多