Java 使用Jersey+;莫西
我正在使用Jersey和MOXy编写REST服务。 我需要创建一个JSON对象数组,如下所示:Java 使用Jersey+;莫西,java,json,jersey,moxy,Java,Json,Jersey,Moxy,我正在使用Jersey和MOXy编写REST服务。 我需要创建一个JSON对象数组,如下所示: { indexes:[ { "name": "ABC", "value": "abcdef" "displayValue": "abcdef", "type": "string" }, { "name": "XYZ", "value": 12345 "displa
{
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”将整数或字符串赋值。
类似地,我定义了getValue以返回整数或字符串
这是我的输出,毫不奇怪,它创建了另一个级别的花括号:
{
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"
},
...
是否有任何方法可以实现我需要的“值”字段的变量类型值?我不确定您的问题到底出在哪里。您使用的是什么JSON库?另外,您能否提供有关索引类的更多详细信息?我不知道为什么你的设置值(对象值)需要做任何特殊的事情。如果我将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"}]
我相信这正是您想要的。谢谢您的回复。是的,你的例子正是我需要的。然而,我不使用Jackson(这不是我的决定),而是使用MOXy为对象生成“类型”;我将POJO作为服务响应返回,以便MOXy在之后发挥其魔力。