1. 程式人生 > >json&xml學習筆記--Java實現xml與json格式的互轉

json&xml學習筆記--Java實現xml與json格式的互轉

寫在前面:

這裡使用的是耗費理解力最少的寫法,不代表最優解或最常用解。

XML轉JSON:

這個功能比JSON轉XML常用。

book.xml

準備好,放於src根目錄下:

<?xml version="1.0" encoding="UTF-8" ?>
<bookstore>
    <book category="COOKING">
      <title lang="en">Everyday Italian</title> 
      <author>Giada De Laurentiis</author> 
      <year>2005</year> 
      <price>30.00</price> 
    </book>
    <book category="CHILDREN">
      <title>哈利波特</title> 
      <author>J·K·羅琳</author> 
      <year>2005</year> 
      <price>29.99</price> 
    </book>
    <book category="WEB">
      <title lang="en">Learning XML</title> 
      <author>Erik T. Ray</author> 
      <year>2003</year> 
      <price>39.95</price> 
    </book>
</bookstore>

jar包:

commons-io-2.6.jar;

org.json-2.0.jar;

Java程式碼:

package books;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class XmlToJson {
	
	public static String xmlToJson() {
		try {
			FileInputStream inputStream = new FileInputStream(new File("src/books.xml"));
			String xmlStr = IOUtils.toString(inputStream,"UTF-8");
			JSONObject object = XML.toJSONObject(xmlStr);
			return object.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	    return null;
	}
	
	public static void main(String[] args) {
		System.out.println(xmlToJson());
	}
}

輸出結果:

{"bookstore":{"book":[{"year":2005,"author":"Giada De Laurentiis","price":30,"category":"COOKING","title":{"lang":"en","content":"Everyday Italian"}},{"year":2005,"author":"J·K·羅琳","price":29.99,"category":"CHILDREN","title":{"lang":"en","content":"哈利波特"}},{"year":2003,"author":"Erik T. Ray","price":39.95,"category":"WEB","title":{"lang":"en","content":"Learning XML"}}]}}

美美噠格式化之後:

{
	"bookstore": {
		"book": [{
			"year": 2005,
			"author": "Giada De Laurentiis",
			"price": 30,
			"category": "COOKING",
			"title": {
				"lang": "en",
				"content": "Everyday Italian"
			}
		}, {
			"year": 2005,
			"author": "J·K·羅琳",
			"price": 29.99,
			"category": "CHILDREN",
			"title": {
				"lang": "en",
				"content": "哈利波特"
			}
		}, {
			"year": 2003,
			"author": "Erik T. Ray",
			"price": 39.95,
			"category": "WEB",
			"title": {
				"lang": "en",
				"content": "Learning XML"
			}
		}]
	}
}

嗯,基本上沒什麼問題,可以直接用了。

JSON轉XML:

books.json

準備好,放於src根目錄下:

{
  "message": "這是一箇中文測試",
  "info": {
    "fileType": "json",
    "fileUsage": "我在哪裡?我要做什麼?"
  },
  "books": [{
    "title": "Everyday Italian",
    "author": "Giada De Laurentiis",
    "year": "2005",
    "price": "30.00"
    },
    {
      "title": "Harry Potter",
      "author": "J K. Rowling",
      "year": "2005",
      "price": "29.99"
    },
    {
      "title": "Learning JSON",
      "author": "Erik T. Ray",
      "year": "2005",
      "price": "39.95"
    }
  ]
}

jar包:

commons-io-2.6.jar;

org.json-2.0.jar;

Java程式碼:

注意這裡的jsonToXmlstr(JSONObject jsonObject, StringBuffer buffer )...

package books;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class JsonToXml {

	public static String jsonToXmlstr(JSONObject jsonObject, StringBuffer buffer ){
		Set<Map.Entry<String, Object>> set = jsonObject.entrySet();
		Iterator<Map.Entry<String, Object>> iterator = set.iterator();
		while (iterator.hasNext()){
			Map.Entry<String, Object> entry = iterator.next();
			if (entry.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONObject")){
				buffer.append("<" + entry.getKey() + ">");
				JSONObject jo = jsonObject.getJSONObject(entry.getKey());
				jsonToXmlstr(jo, buffer);
				buffer.append("</" + entry.getKey() + ">");
			} else if(entry.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONArray")){
				JSONArray ja = jsonObject.getJSONArray(entry.getKey());
				for (int i = 0; i < ja.size(); i++) {
					buffer.append("<" + entry.getKey() + ">");
					JSONObject joChild = ja.getJSONObject(i);
					jsonToXmlstr(joChild, buffer);
					buffer.append("</" + entry.getKey() + ">");
				}
			} else if(entry.getValue().getClass().getName().equals("java.lang.String")){
				buffer.append("<" + entry.getKey() + ">" + entry.getValue());
				buffer.append("</" + entry.getKey() + ">");
			}
		}
		return buffer.toString();
	}

	public static String jsonToXml() {
		try {
			String jsonStr = FileUtils.readFileToString(new File("src/books.json"), "UTF-8");
			JSONObject jsonObject = JSON.parseObject(jsonStr);

			StringBuffer buffer = new StringBuffer();
			buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

			return jsonToXmlstr(jsonObject, buffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(jsonToXml());
	}

}

注意:

​ 這裡jsonToXmlstr方法遍歷非字串資料型別時,可能造成資料丟失,因為葉子結點資料型別的判斷條件是equals("java.lang.String")嘛 U know~

輸出結果:

<?xml version="1.0" encoding="utf-8"?><books><year>2005</year><author>Giada De Laurentiis</author><price>30.00</price><title>Everyday Italian</title></books><books><year>2005</year><author>J K. Rowling</author><price>29.99</price><title>Harry Potter</title></books><books><year>2005</year><author>Erik T. Ray</author><price>39.95</price><title>Learning JSON</title></books><message>這是一箇中文測試</message><info><fileUsage>我在哪裡?我要做什麼?</fileUsage><fileType>json</fileType></info>

開森噠格式化之後:

<?xml version="1.0" encoding="utf-8"?>
<books>
	<year>2005</year>
	<author>Giada De Laurentiis</author>
	<price>30.00</price>
	<title>Everyday Italian</title>
	</books>
<books>
	<year>2005</year>
	<author>J K. Rowling</author>
	<price>29.99</price>
	<title>Harry Potter</title>
</books>
<books>
	<year>2005</year>
	<author>Erik T. Ray</author>
	<price>39.95</price>
	<title>Learning JSON</title>
</books>

<message>這是一箇中文測試</message>

<info>
	<fileUsage>我在哪裡?我要做什麼?</fileUsage>
	<fileType>json</fileType>
</info>

——發現一個開森不起來的問題:

​ 程式碼完美地將json資料轉化為了xml格式,但是這並不是一個符合xml文件結構的xml。

​ 原因:xml是樹形結構,是有根元素的。如果原生的json資料不遵循這個原則,那麼生成的xml文件就是不規範的,需要開發者根據具體情況改進上述java程式碼,或生成結果