我正在将 Xstream 1.3 升级到 1.4。但是我发现生成的 JSON 不正确,我不确定我需要做什么来解决这个问题。我写了一个 JUNIT 测试并且能够重现这个问题。这是测试的代码
public class XstreamTest {
@Test
public void testXstreamStuffForBasicVO(){
BasicVO basicVO = new BasicVO("atttr1", "attr2");
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
//XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.registerConverter(new BasicVOConverter());
System.out.println(xstream.toXML(basicVO));
//return setupXstream(xstream);
}
class BasicVO{
@XStreamAlias("alias1")
private String attribute1;
@XStreamAlias("alias2")
private String attribute2;
BasicVO(String att1, String att2){
setAttribute1(att1);
setAttribute2(att2);
}
BasicVO(){
}
public String getAttribute1() {
return attribute1;
}
public void setAttribute1(String attribute1) {
this.attribute1 = attribute1;
}
public String getAttribute2() {
return this.attribute2;
}
public String getAttribute3(){
return "madeupAttribute";
}
public void setAttribute2(String attribute2) {
this.attribute2 = attribute2;
}
}
class BasicVOConverter implements Converter{
@Override
public boolean canConvert(Class type) {
return BasicVO.class.isAssignableFrom(type);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
BasicVO basicVO = (BasicVO) source;
writer.startNode("property1");
writer.setValue(basicVO.getAttribute1());
writer.endNode();
writer.startNode("property2");
writer.setValue(basicVO.getAttribute2());
writer.endNode();
writer.startNode("property3");
writer.setValue(basicVO.getAttribute3());
writer.endNode();
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
BasicVO person = new BasicVO();
reader.moveDown();
person.setAttribute1(reader.getValue());
reader.moveUp();
reader.moveDown();
person.setAttribute2(reader.getValue());
reader.moveUp();
return person;
}
}
}
生成的输出是以下无效 JSON(无效,因为值不在双引号内)
{"com.xyz.XstreamTest$BasicVO": {
"property1": atttr1,
"property2": attr2,
"property3": madeupAttribute
}}
我想指出的是,当我使用 JettisonMappedXmlDriver 时,这不是问题,但是,我不能使用它,因为我失去了使用 JsonHierarchicalStreamDriver 获得的其他一些重要的东西。
使用 Xstream 1.3,我得到以下信息
{"com.xyz.XstreamTest$BasicVO": {
"property1": "atttr1",
"property2": "attr2",
"property3": "madeupAttribute"
}}
我浏览了 Xstream 1.4 和 1.3 的代码,发现了显着的差异。此外,我发现引用逻辑的应用方式存在差异。在 1.3 中,更普遍地添加了引号。但是在 1.4 中,仅为“字符串”类型添加引号,我不确定这是如何确定的。
我倾向于 xstream 1.4 代码中的一些错误?这似乎太牵强了,我可能错过了一些步骤。谁能帮我解决这个问题?谢谢