【问题标题】:Format nested JSON response格式化嵌套的 JSON 响应
【发布时间】:2012-01-17 06:50:13
【问题描述】:

我在将 JSON 格式化为响应数据时遇到问题。我有一个 Player 类,其中包含字段名称、id、年龄、顶部、中间和底部。我有另一个类 Position,它具有字段 id、top、middle 和 bottom。玩家字段 top、middle 和 bottom 来自 Position 并为 Player 设置。

我的问题是我得到 JSON 响应数据:

{ id     : 10,
  age    : 16,
  top    : 18,
  middle : 16,
  bottom : 10
}

而我希望它是:

 { id  : 10,
   age : 16,
   position : {
     top    : 18,
     middle : 16,
     bottom : 10
   }
 }

【问题讨论】:

  • 它取决于你的数组形成
  • 您从哪里得到回复?您使用什么服务器端语言来生成此输出?是 PHP、Ruby、VB.NET/C# 吗?
  • diEcho:这不是数组,实际上是其他类的字段。
  • NoLifeKing:我正在使用 java RestEasy api
  • 那么您应该能够设置播放器类以包含位置作为属性。 :)

标签: java json hibernate rest


【解决方案1】:

您还没有说明 JSON 对象是如何生成为输出的。在这里,您可以通过组织返回的输出中的数据来根据需要创建新的 JSON 对象,如下所示:

var returned={
    "id": 10,
    "age": 16,
    "top": 18,
    "middle": 16,
    "bottom": 10
};

var iWanted={
  "id":returned["id"],
  "age":returned["age"],
  "position":{
        "top":returned["top"],
        "middle":returned["middle"],
        "bottom":returned["bottom"]
      }
};

console.log(iWanted);

【讨论】:

  • Json 对象是使用 restAPI @Produces("application/json") 创建的。
  • 我没有得到如何转换返回为 iWanted 使用它
  • 你能将 restAPI 响应分配给任何变量吗?您能否详细说明restAPI中的响应是如何完成的?
猜你喜欢
  • 1970-01-01
  • 2017-07-30
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 2020-12-31
  • 2018-08-02
相关资源
最近更新 更多