XStream:将JSON解析为具有JSONObject字段的类

时间:2014-03-19 14:41:29

标签: java json xstream

我需要用XStream解析JSON,其中一个类有一个JSONObject字段,XStream应该直接将JSON转储到它中。但是,XStream(当前使用1.4.1)尝试解析该JSON并因UnknownFieldException而失败。这是孤立的代码:

class Container {
    public JSonObject data = null;
}

public class TestXStreamJson {
    public String testRequest = "{\"container\":{\"data\":{\"FirstName\":\"John\",\"LastName\":\"Doe\"}}}";

    @Test
    public void test() throws Exception {
        XStream xs = new XStream(new JettisonMappedXmlDriver());
        xs.setMode(XStream.NO_REFERENCES);
        xs.alias("container", Container.class);
        Object x = xs.fromXML(testRequest);
        System.out.println(x);
    }
}

XStream的结果堆栈跟踪:

com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field org.json.JSONObject.FirstName
---- Debugging information ----
field               : FirstName
class               : org.json.JSONObject
required-type       : org.json.JSONObject
converter-type      : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
line number         : -1
class[1]            : com.genesyslab.brs.api.Container
version             : null
-------------------------------
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.determineType(AbstractReflectionConverter.java:449)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:290)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:230)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshallField(AbstractReflectionConverter.java:351)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:302)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:230)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
    at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1035)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1019)
    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:895)
    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:886)

0 个答案:

没有答案