要解析为对象的自定义JSON数据

时间:2016-02-13 13:23:03

标签: json

我有将此任务解析为对象的json数据,如

    {
"AAA" : {
       "A1" : "a1 comment",
       "A2" : "a2 comment"   
    },
"BBB" : {
      "B1" : "b1 comment"
    },
"CCC" : {
      "C1" : "c1 comment",
       "C2" : "c2 comment",
       "C3" : "c3 comment"
       "C4" : "c4 cooment"
    },
"DDD" : {
      "D1" : "d1 comment"
    }
}

需要转换为像

这样的对象
class Schema {
    String tableName;
    List<Column> colData;

class Column {

    String columnName;
    String columnComments;

因为我是json的初学者,所以我采用了首先将事物解析为xml的方法,如果有效,则继续将xml解析为object。

但是我在解析json数据时遇到了问题。

但是如果我用双引号替换所有单引号并且&#39; =&gt;&#39;用&#39;:&#39;并且只考虑AAA,我能够使用下面的代码进行解析,但是如果我使用整个json数据则会抛出错误。

非常感谢任何帮助。

我到目前为止的代码是:

FileInputStream fis = new FileInputStream(new File("schema.sql"));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
            InputSource source = new InputSource(new StringReader(IOUtils.toString(fis, "UTF-8")));
            DOMResult result = new DOMResult();
            transformer.transform(new SAXSource(new JsonXmlReader("Table"), source), result);
            Node n=result.getNode();
            System.out.println(result.toString());

            StringWriter writer = new StringWriter();
//          Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform(new DOMSource(n), new StreamResult(writer));
            String xml = writer.toString();
            System.out.println(xml);

适用于以下数据:

{
"AAA" : {
       "A1" : "a1 comment",
       "A2" : "a2 comment"   
    }
}
当然,我必须更换所有&#39;用&#34;和=&gt;用:

用于json数据

{
"AAA" : {
       "A1" : "a1 comment",
       "A2" : "a2 comment"   
    },
"BBB" : {
      "B1" : "b1 comment"
    }
}

我看到的错误是:

ERROR:  'Parsing error: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. '
javax.xml.transform.TransformerException: net.javacrumbs.json2xml.JsonSaxAdapter$ParserException: Parsing error: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. 
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)


net.javacrumbs.json2xml.JsonSaxAdapter$ParserException: Parsing error: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. 
    at net.javacrumbs.json2xml.JsonSaxAdapter.parse(JsonSaxAdapter.java:177)
    at net.javacrumbs.json2xml.JsonXmlReader.parse(JsonXmlReader.java:152)

0 个答案:

没有答案