【问题标题】:My json missing [ ] for a list in Restful Api [duplicate]我的 json 在 Restful Api 中缺少 [] [重复]
【发布时间】:2015-09-01 10:08:36
【问题描述】:

我正在开发一个应该返回 json 数据的 restful api。

我的服务是这样的:

@Path("tfs/projectRegStatus")
public class ProjectRegStatusService {      

    @GET
    @Path("/QA")
    @Produces(MediaType.APPLICATION_JSON)
    public ProjectRegStatusVO getProjectRegStatusQA(){
        return ProjectRegStatusModule.getInstance().getProjectRegResult("QA").produceNumber();
    }

而实体ProjectRegStatusVO是这样的:

@XmlRootElement

public class ProjectRegStatusVO {
    private String name;
    private int colorValue;
    private List<ProjectRegStatusVO> children;
}

而我的问题是,当我们只有一个孩子时,JSON 数据应该是这样的:

{
  "name": "SpecPool Risk",
  "colorValue": 48,
  "children": [
    {
      "name": "Hedge Sheet",
      "colorValue": 48
    }
  ]
}

但这就是我得到的

{ 
  "name": "SpecPool Risk", 
  "colorValue": 48, 
  "children": { 
    "name": "Hedge Sheet", 
    "colorValue": 48 
  } 
}

子列表中必须有[],即使它只有一个子。

但我的结果在子列表中没有[]。

你们能帮忙吗?

【问题讨论】:

  • 你使用的是什么 JSON 库?
  • 您的 children 元素已经是一个 JSON 数组。这里有什么问题?
  • public class ProjectRegStatusVO { public ProjectRegStatusVO(){ children = new ArrayList(); } public ProjectRegStatusVO(String name, int colorValue){ this.name = name; this.colorValue = colorValue; children = new ArrayList(); } public ProjectRegStatusVO(String name, int colorValue,List&lt;ProjectRegStatusVO&gt; children){ this.name = name; this.colorValue = colorValue; this.children = children; } public List&lt;ProjectRegStatusVO&gt; getChildren() { return children; } public void setChildren(List&lt;ProjectRegStatusVO&gt; children) { this.children = children; } 是这样吗?
  • 我想要这个 { "name": "SpecPool Risk", "colorValue": 48, "children": [ { "name": "Hedge Sheet", "colorValue": 48 } ] } 而不是 { "name": "SpecPool Risk", "colorValue": 48, "children": { "name": "Hedge Sheet", "colorValue": 48 } }
  • 我只是在我的服务中设置了媒体类型,如import javax.ws.rs.core.MediaType; 和@Produces(MediaType.APPLICATION_JSON),这样我就可以返回一个实体并将其转换为 json。第二个很好,但是即使列表中只有一个,前端也需要 [] 在每个孩子中。

标签: java json api rest jersey


【解决方案1】:

这可能会有所帮助:

private List<ProjectRegStatusVO> children = new ArrayList<ProjectRegStatusVO>(); //Or Diamond Operator if using Java 7 and upward.

或者,在您的 getter 方法中,如果 children 是 null,则返回一个空的 List。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2015-06-19
    • 2019-05-04
    • 2017-12-06
    • 2015-08-16
    • 2011-12-01
    相关资源
    最近更新 更多