【问题标题】:Is there a way to remove just a field name from json object generate through Spring?有没有办法从通过 Spring 生成的 json 对象中删除字段名称?
【发布时间】:2020-03-28 11:10:58
【问题描述】:

我正在开发一个示例应用程序来学习 Spring。我希望我的服务以以下格式返回结果。

{
  [
    {
      "name": "John",
      "age": "25"
    },
    {
      "name": "Jack",
      "age": "20"
    }
  ]
}

我设计了一个这样的类来存储关于一个人的数据。

class Person {
  String name;
  String age;
  //getters and setters
}

另一个持有 Person 数组的类

class Result {
  ArrayList<Person> result = new ArrayList();

  void addPerson(Person p) {
      result.add(p);
  }
  //getter for result
}

当我调用我的 API 时,我得到以下格式的结果。

{
  "result": [
    {
      "name": "John",
      "age": "25"
    },
    {
      "name": "Jack",
      "age": "20"
    }
  ]
}

如何使“结果”字符串远离结果?是不是我设计错了?

谢谢

【问题讨论】:

  • 你不能。您想要获得的(在第一个示例中)不是合法的 json。

标签: java spring spring-boot rest api


【解决方案1】:

您可以使用@JsonValue 将数组作为根元素

class Result {
  @JsonValue
  ArrayList<Person> result = new ArrayList();

  ...
}

输出json:

  [
    {
      "name": "John",
      "age": "25"
    },
    {
      "name": "Jack",
      "age": "20"
    }
  ]

您的 json {[...]} 不是有效的 json

【讨论】:

    猜你喜欢
    • 2020-02-27
    • 1970-01-01
    • 2023-01-11
    • 2019-10-07
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多