从XML到JSON的隐蔽响应

时间:2016-11-17 06:35:35

标签: java json xml

我已经制作了一个小程序,用于测试将xml转换为json。 正如

public $fixtures = [
    'app.articles',
    'app.authors',
];

...

public function setUp()
{
    $connection = \Cake\Datasource\ConnectionManager::get('test');
    foreach ($this->fixtures as $fixture) {
        $tableName = explode('.', $fixture)[1];
        $connection->execute("
            SELECT setval(
                pg_get_serial_sequence('$tableName', 'id'),
                (SELECT MAX(id) FROM $tableName)
            )");
    }
}

但问题是我无法导入org.json.XML。虽然能够导入org.json.jsonobject。 这是依赖性的问题吗?

2 个答案:

答案 0 :(得分:0)

添加以下依赖关系,

import org.json.JSONObject;
import org.json.XML;

Jar java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

<强>的Maven

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20131018</version>
</dependency>

以下是代码

import org.json.JSONObject;
import org.json.XML;

public class Test {

    private static final String XML_TEXT = "<note>\n" + "<to>Tove</to>\n" + "<from>Jani</from>\n"
            + "<heading>Reminder</heading>\n" + "<body>Don't forget me this weekend!</body>\n" + "</note>";
    private static final int i = 4;

    public static void convert() {
        JSONObject xmlJSONObj = XML.toJSONObject(XML_TEXT);
        String jsonPrettyPrintString = xmlJSONObj.toString(i);
        System.out.println(jsonPrettyPrintString);
    }
    public static void main(String[] args) {
        convert();
    }
}

<强>输出

{"note": {
    "heading": "Reminder",
    "from": "Jani",
    "to": "Tove",
    "body": "Don't forget me this weekend!"
}}

答案 1 :(得分:0)

程序运行正常,唯一缺少的是你还没有添加以下jar:

java-json.jar

您已发布的程序,我能够正常运行它:

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class XMLtoJSON {
    private static final String XML_TEXT = "<note>\n" + "<to>Tove</to>\n" + "<from>Jani</from>\n"
            + "<heading>Reminder</heading>\n" + "<body>Don't forget me this weekend!</body>\n" + "</note>";
    private static final int i = 4;

    public static void convert() {
        JSONObject xmlJSONObj;
        String jsonPrettyPrintString = null;
        try {
            xmlJSONObj = XML.toJSONObject(XML_TEXT);
            jsonPrettyPrintString = xmlJSONObj.toString(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(jsonPrettyPrintString);
    }
    public static void main(String[] args) {
        convert();
    }
}

该计划的输出符合预期:

{"note": {
    "heading": "Reminder",
    "from": "Jani",
    "to": "Tove",
    "body": "Don't forget me this weekend!"
}}

Maven依赖:

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>