【问题标题】:Spring sends empty JSON despite of object being not null尽管对象不为空,Spring 仍发送空 JSON
【发布时间】:2019-07-10 14:36:24
【问题描述】:

在我的控制器中,我有以下方法:

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    public List<Topic> getAllTopics() {

        List<Topic> allTopics = service.getAllTopics();

        assert allTopics.size() > 0; // is not empty
        System.out.println(allTopics.get(0)); // Topic{id=1, name='bla', description='blahhh'}

        return allTopics;
    }

当我转到http://localhost:8080/getAll 时,我得到[{},{},{},{}],但service.getAllTopics() 返回非空列表所以要发送的列表不为空,但浏览器接收到无效的JSON。但是,序列化对象没有问题,因为以下方法返回有效的 JSON。有什么问题?

    @GetMapping("/json")
    public List<Locale> getLocales() {
        return Arrays.asList(DateFormat.getAvailableLocales());
    }

我正在运行最新的 Spring Boot,即 2.1.3.RELEASE。

更新 这是我的实体类 - 主题

@Entity
@Table(name = "topic", schema="tetra")
public class Topic {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String description;

    public Topic() {
    }

    public Topic(String name, String description) {
        this.name = name;
        this.description = description;
    }

    @Override
    public String toString() {
        return "Topic{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

【问题讨论】:

  • Topic 看起来怎么样?
  • @KenChan 请查看我的更新答案。

标签: json spring-boot spring-data-jpa


【解决方案1】:

默认情况下,Jackson 只会将公共字段和公共 getter 序列化为 JSON。由于 Topic 既没有公共字段也没有公共 getter ,因此不会序列化任何内容,您会得到一个空的 JSON 对象。

有很多方法可以配置它,例如:

(1) 只需为所有字段添加公共 getter

(2) 使用@JsonAutoDetect(fieldVisibility = Visibility.ANY) 这样也可以自动检测私有字段:

@Entity
@Table(name = "topic", schema="tetra")
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class Topic {


}  

(3) 使用@JsonProperty 明确选择要序列化的字段/getter。这种方法的好处是JSON 中的字段名称可以与POJO 不同:

@Entity
@Table(name = "topic", schema="tetra")
public class Topic {

   @JsonProperty("id")
   private Integer id;

   @JsonProperty("name")
   private String name;

   @JsonProperty("description")
   private String description;
}

【讨论】:

  • 我的愚蠢错误。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-05
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多