Efficient parser to convert XML to JSON in java without JsonObject and Array

时间:2017-12-18 07:18:44

标签: java json xml stax

I tried to convert XML to JSON in java. I am using Stax parser for Conversion. After getting START_ELEMENT, END_ELEMENT, CHARACTERS, I don't know how to convert it to JSON Format. Not use any inbuilt libraries, JsonObject, JSonArray.IS any logic available For this conversion...

3 个答案:

答案 0 :(得分:2)

Why not use already existing JARs to do the job.
One such efficient parser is present in java-json http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

Conversion can be done in one line using

import org.json.XML;

....

JSONObject jsonObject = XML.toJSONObject("Your XML Here");

答案 1 :(得分:1)

将XML转换为JSON的示例代码。由于我正在创建一个Java项目,所以在eclipse中创建一个Java项目。我将通过右键单击该项目来手动导入Java-json.jar,然后通过选择添加外部jar选项来选择配置构建路径,然后添加jar文件并运行项目。如果要使用maven项目进行构建,请在pom.xml中添加以下依赖项

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

package com.test.jsontoxml
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class JsonConversion {

 public static int PRETTY_PRINT_INDENT_FACTOR = 4;
    public static String TEST_XML_STRING =
        "<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";

    public static void main(String[] args) {
        try {
            JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
            String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
            System.out.println(jsonPrettyPrintString);
        } catch (JSONException je) {
            System.out.println(je.toString());
        }
    }
}

答案 2 :(得分:0)

Underscore-java库可以将xml转换为json。我是该项目的维护者。 Live example

import com.github.underscore.lodash.U;

public class JsonConversion {
    public static String TEST_XML_STRING =
        "<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";
    public static void main(String args[]) {
        String jsonPrettyPrintString = U.xmlToJson(TEST_XML_STRING);
        System.out.println(jsonPrettyPrintString);
        // {
        //   "test": {
        //     "-attrib": "moretest",
        //     "#text": "Turn this to JSON"
        //   }
        // }
    }
}