【发布时间】: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<ProjectRegStatusVO> children){ this.name = name; this.colorValue = colorValue; this.children = children; } public List<ProjectRegStatusVO> getChildren() { return children; } public void setChildren(List<ProjectRegStatusVO> 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。第二个很好,但是即使列表中只有一个,前端也需要 [] 在每个孩子中。