我需要将 Java 对象转换为 JSON 字符串。这是我使用的代码,例如:
public class XstreamTest {
public static void main(String[] args) throws Exception {
Order order = new Order();
order.id = 1;
order.products = new ArrayList<Product>();
Product prod1 = new Product();
prod1.barCode = "4821111111111";
Product prod2 = new Product();
prod2.barCode = "4821111111112";
order.products.add(prod1);
order.products.add(prod2);
System.out.println(toJson(order));
}
public static String toJson(Object document) throws Exception {
XStream xstream = new XStream(new JettisonMappedXmlDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.autodetectAnnotations(true);
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias(document.getClass().getSimpleName(),
document.getClass());
return xstream.toXML(document);
}
}
@XStreamAlias("ORDER")
class Order {
@XStreamAlias("NUMBER")
public int id;
@XStreamAlias("PRODUCT")
@XStreamImplicit(itemFieldName="PRODUCT")
public List<Product> products;
}
class Product {
@XStreamAlias("BARCODE")
public String barCode;
}
运行后,我有结果:
{
"NUMBER": 1,
"PRODUCT": {
"BARCODE": "4821111111111"
},
"PRODUCT": {
"BARCODE": "4821111111112"
}
}
我在http://www.jslint.com/上检查 json并得到错误:重复的“产品”。
请帮忙!我做错了什么?或者可能是 XStream 中的错误?