2014-03-25 37 views
0

我有以下XML实体:ClassCastException异常解组时JSON

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlRootElement 
public class DocumentDossier { 

    private XdsJsonSubmissionSet submissionSet; 
    private XdsJsonDocument documentEntry; 
    private List<XdsJsonFolder> folder; 
    private List<XdsJsonAssociation> association; 
    ... 

我试图来解读下列方式一个JSON文件:

String content = IOUtils.toString(is); 
    JSONObject obj = new JSONObject(content); 
    Configuration config = new Configuration(); 
    MappedNamespaceConvention con = new MappedNamespaceConvention(config); 
    XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(obj, con); 

    JAXBContext jc = JAXBContext.newInstance(DocumentDossier.class); 
    Unmarshaller unmarshaller = jc.createUnmarshaller(); 
    DocumentDossier result = (DocumentDossier) unmarshaller.unmarshal(xmlStreamReader); 

但JSON我需要来解读没有根节点,这就是它应该的方式。这里的JSON问题:

{ 
    "submissionSet": {...}, 
    "documentEntry": {...}, 
    "association": {...} 
} 

使用此代码,我得到以下错误:

java.lang.ClassCastException: XdsJsonSubmissionSet cannot be cast to DocumentDossier 

有什么不对?

+1

你的问题没有意义:有一个隐含的根节点(外层'{}'实际上是一个JSON“对象”),你需要将其元素映射到'DocumentDossier'中的字段。所以这应该已经可以工作了。你有错误吗?或者你想跳过什么? –

+0

我得到以下错误: java.lang.ClassCastException:XdsJsonSubmissionSet不能转换到DocumentDossier 我想跳过是有我的JSON对象包裹在{“documentDossier”:...},所以我的Web服务将能够接收像我发布的JSON对象。 – user2451415

+0

如果你用'{“documentDossier”:...}来包装你的JSON,你需要另一个包装'DocumentDossier'的Java类来解析JSON。上面的JSON应该已经映射到'DocumentDossier'。错误必须有不同的原因。 –

回答

0

我认为你需要为每个字段添加@XmlElement

另外不要忘记添加@XmlRootElementXdsJsonSubmissionSet@XmlElement到其领域。

+0

这并没有解决我的问题,而是决定将JSON作为InputStream传递给我的代码,并将其包装在“documentDossier”中:{...}。不管怎么说,还是要谢谢你! – user2451415

+0

这个包装是绝对没有必要的。你是否尝试在编组一个'DocumentDossier'时获得哪个输出? –