我的Java代码返回一个Collection(ArrayList),由JAXB生成的结果JSON如下所示:
{"todo":[{"name":"CAMPBELL","sales":"3","time":"1331662363931"},
{"name":"FRESNO","sales":"2","time":"1331662363931"}]}
但是,有没有办法让它看起来像:
[{"name":"CAMPBELL","sales":"3","time":"1331662363931"},
{"name":"FRESNO","sales":"2","time":"1331662363931"}]
在Java / JAXB中是否存在某种方式,或者使用responseText可能在AJAX回调中。 。
顺便说一下,我也尝试过使用Java数组,但它没有任何区别。任何帮助将不胜感激。
答案 0 :(得分:1)
答案 1 :(得分:0)
注意:我是EclipseLink JAXB (MOXy)主管,是JAXB 2 (JSR-222)专家组的成员。
您可以在服务器上修复问题,而不是在客户端上更正错误的JSON。下面是EclipseLink JAXB(MOXy)如何用于生成所需JSON的示例:
<强>演示强>
package forum9689970;
import java.io.StringReader;
import java.util.List;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(SalesPerson.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty("eclipselink.media-type", "application/json");
unmarshaller.setProperty("eclipselink.json.include-root", false);
String jsonString = "[{\"name\":\"CAMPBELL\",\"sales\":\"3\",\"time\":\"1331662363931\"},{\"name\":\"FRESNO\",\"sales\":\"2\",\"time\":\"1331662363931\"}]";
StreamSource json = new StreamSource(new StringReader(jsonString));
List<SalesPerson> salesPeople = (List<SalesPerson>) unmarshaller.unmarshal(json, SalesPerson.class).getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.setProperty("eclipselink.json.include-root", false);
marshaller.marshal(salesPeople, System.out);
}
}
<强>业务员强>
package forum9689970;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class SalesPerson {
private String name;
private String sales;
private String time;
}
<强>输出强>
[ {
"name" : "CAMPBELL",
"sales" : "3",
"time" : "1331662363931"
}, {
"name" : "FRESNO",
"sales" : "2",
"time" : "1331662363931"
} ]
了解更多信息