我正在使用Jersey和MOXy编写REST服务。 我需要创建一个如下所示的JSON对象数组:
{
indexes:[
{
"name": "ABC",
"value": "abcdef"
"displayValue": "abcdef",
"type": "string"
},
{
"name": "XYZ",
"value": 12345
"displayValue": "12345",
"type": "number"
},
...
]
}
应该引用字符串类型,而“数字”类型应该不引用。
我尝试在服务请求中返回以下POJO:
public class Index {
String name;
Object value;
String displayValue;
String type;
}
我定义了setValue,根据“type”为Integer或String赋值。 同样,我将getValue定义为返回Integer或String。
这是我的输出,毫不奇怪,它会创建另一个花括号:
{
indexes:[
{
"name": "ABC",
"value": {
"type": "xsd:string",
"value": "abcdef"
},
"displayValue": "abcdef",
"indexType": "string"
},
{
"name": "XYZ",
"value": {
"type": "xsd:int",
"value": 812501
},
"displayValue": "812501",
"indexType": "number"
},
...
有没有办法实现我所需要的,“值”字段的变量类型值?
答案 0 :(得分:0)
我不确定你的问题究竟在哪里。您使用的JSON库是什么?另外,您能否提供有关Index类的更多详细信息?我不确定为什么你的setValue(对象值)需要做任何特殊的事情。如果我使用带有以下代码的Jackson json库:
public static void main(String[] args) throws JsonProcessingException {
Index[] indices = new Index[2];
indices[0] = new Index();
indices[0].name = "ABC";
indices[0].value = "abcdef";
indices[0].displayValue = indices[0].value + "";
indices[0].type = "string";
indices[1] = new Index();
indices[1].name = "XYZ";
indices[1].value = 123456;
indices[1].displayValue = indices[1].value + "";
indices[1].type = "number";
System.out.println(new ObjectMapper().writeValueAsString(indices));
}
public static class Index {
String name;
Object value;
String displayValue;
String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getDisplayValue() {
return displayValue;
}
public void setDisplayValue(String displayValue) {
this.displayValue = displayValue;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
我得到以下输出:
[{"name":"ABC","value":"abcdef","displayValue":"abcdef","type":"string"},
{"name":"XYZ","value":123456,"displayValue":"123456","type":"number"}]
我相信你正在寻找的东西。