java 把xml转化为json

java 中如何把xml转化为json 呢?

常规思路是:

(1)通过第三方库 把xml 转换为java bean;

(2)把java bean 序列化为json 字符串

但是上述方式有一个缺点,那就是需要java bean来中转.

以下提供两种方式 不需要java bean

方式一:使用json-lib

 

XMLSerializer xmlSerializer = new XMLSerializer();
		JSON jsonObj = xmlSerializer.read(responseTextObj);
		String jsonStr = jsonObj.toString();
		jsonStr = jsonStr.replace("[]", "\"\"");

 依赖:

<dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>
            <version>1.2.5</version>
        </dependency>

        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>
            <version>1.2.5</version>
            <classifier>sources</classifier>
        </dependency>

 注意:通过json-lib 把xml转化为json时,空节点都会转化为空数组,即[],这是非常不好的,所以需要把[]转化为空字符串:jsonStr.replace("[]", "\"\"")

 参考:http://hw1287789687.iteye.com/blog/2224407

方式二:使用github 上开源的库

package com.JSON_java;

public class Main {
	public static int PRETTY_PRINT_INDENT_FACTOR = 4;
    public static String TEST_XML_STRING =
            "<breakfast_menu>\n" +
                    "<food>\n" +
                    "<name>Belgian Waffles</name>\n" +
                    "<price>$5.95</price>\n" +
                    "<description>\n" +
                    "Two of our famous Belgian Waffles with plenty of real maple syrup\n" +
                    "</description>\n" +
                    "<calories>650</calories>\n" +
                    "</food>\n" +
                    "<food>\n" +
                    "<name>Strawberry Belgian Waffles</name>\n" +
                    "<price>$7.95</price>\n" +
                    "<description>\n" +
                    "Light Belgian waffles covered with strawberries and whipped cream\n" +
                    "</description>\n" +
                    "<calories>900</calories>\n" +
                    "</food>\n" +
                    "</breakfast_menu>";

    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());
        }
    }
}

实际应用:

 

依赖的源码见附件 ,上述代码见附件中的Main.java

github 地址:https://github.com/douglascrockford/JSON-java

https://github.com/douglascrockford/JSON-java/blob/master/XML.java

参考:http://heshans.blogspot.com/2014/01/java-library-to-convert-xml-to-json.html

猜你喜欢

转载自hw1287789687.iteye.com/blog/2229267