1. 程式人生 > >json、javaBean、xml互轉的幾種工具介紹

json、javaBean、xml互轉的幾種工具介紹

工作中經常要用到Json、JavaBean、Xml之間的相互轉換,用到了很多種方式,這裡做下總結,以供參考。

現在主流的轉換工具有json-lib、jackson、fastjson等,我為大家一一做簡單介紹,主要還是以程式碼形式貼出如何簡單應用這些工具的,更多高階功能還需大家深入研究。

首先是json-lib,算是很早的轉換工具了,用的人很多,說實在現在完全不適合了,缺點比較多,依賴的第三方實在是比較多,效率低下,API也比較繁瑣,說他純粹是因為以前的老專案很多人都用到它。不廢話,開始上程式碼。

需要的maven依賴:

	<!-- for json-lib -->
	<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.1</version>
	</dependency> 
	<dependency>
		<groupId>xalan</groupId>
		<artifactId>xalan</artifactId>
		<version>2.7.1</version>
	</dependency>

使用json-lib實現多種轉換
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.text.Document;
import net.sf.ezmorph.Morpher;
import net.sf.ezmorph.MorpherRegistry;
import net.sf.ezmorph.bean.BeanMorpher;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.JSONUtils;
import net.sf.json.xml.XMLSerializer;

/**
 * json-lib utils
 * @author magic_yy
 * @see json-lib.sourceforge.net/
 * @see https://github.com/aalmiray/Json-lib
 *
 */
public class JsonLibUtils {
	
	public static JsonConfig config = new JsonConfig();
	
	static{
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);//忽略迴圈,避免死迴圈
    	config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {//處理Date日期轉換
			@Override
			public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
				 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	                Date d=(Date) arg1;
	                return sdf.format(d);
			}
			@Override
			public Object processArrayValue(Object arg0, JsonConfig arg1) {
				return null;
			}
		});
	}
	
	/** 
     * java object convert to json string
     */  
    public static String pojo2json(Object obj){
        return JSONObject.fromObject(obj,config).toString();//可以用toString(1)來實現格式化,便於閱讀  
    }  
      
    /** 
     * array、map、Javabean convert to json string
     */  
    public static String object2json(Object obj){  
        return JSONSerializer.toJSON(obj).toString();  
    }  
      
    /** 
     * xml string convert to json string
     */  
    public static String xml2json(String xmlString){  
        XMLSerializer xmlSerializer = new XMLSerializer();  
        JSON json = xmlSerializer.read(xmlString);  
        return json.toString();  
    }  
      
    /** 
     * xml document convert to json string
     */  
    public static String xml2json(Document xmlDocument){  
        return xml2json(xmlDocument.toString());  
    }  
      
    /** 
     * json string convert to javaBean
     * @param <T>
     */  
    @SuppressWarnings("unchecked")
	public static <T> T json2pojo(String jsonStr,Class<T> clazz){  
        JSONObject jsonObj = JSONObject.fromObject(jsonStr);  
        T obj = (T) JSONObject.toBean(jsonObj, clazz);  
        return obj;  
    }
    
    /**
     * json string convert to map
     */
    public static Map<String,Object> json2map(String jsonStr){
    	JSONObject jsonObj = JSONObject.fromObject(jsonStr);
    	Map<String,Object> result = (Map<String, Object>) JSONObject.toBean(jsonObj, Map.class);
    	return result;
    }
    
    /**
     * json string convert to map with javaBean
     */
    public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz){
    	JSONObject jsonObj = JSONObject.fromObject(jsonStr);
    	Map<String,T> map = new HashMap<String, T>();
    	Map<String,T> result = (Map<String, T>) JSONObject.toBean(jsonObj, Map.class, map);
    	MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
    	Morpher dynaMorpher = new BeanMorpher(clazz,morpherRegistry);
    	morpherRegistry.registerMorpher(dynaMorpher);
    	morpherRegistry.registerMorpher(new DateMorpher(new String[]{ "yyyy-MM-dd HH:mm:ss" }));
    	for (Entry<String,T> entry : result.entrySet()) {
			map.put(entry.getKey(), (T)morpherRegistry.morph(clazz, entry.getValue()));
		}
    	return map;
    }
      
    /** 
     * json string convert to array
     */  
    public static Object[] json2arrays(String jsonString) {  
    	JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(jsonString);
//    	JSONArray jsonArray = JSONArray.fromObject(jsonString);  
    	JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);
    	Object[] objArray = (Object[]) JSONSerializer.toJava(jsonArray,jsonConfig);
        return objArray;
    }  
      
    /** 
     * json string convert to list
     * @param <T>
     */  
    @SuppressWarnings({ "unchecked", "deprecation" })
	public static <T> List<T> json2list(String jsonString, Class<T> pojoClass){  
        JSONArray jsonArray = JSONArray.fromObject(jsonString);  
        return JSONArray.toList(jsonArray, pojoClass);
    }  
      
    /** 
     * object convert to xml string
     */  
    public static String obj2xml(Object obj){  
        XMLSerializer xmlSerializer = new XMLSerializer();  
        return xmlSerializer.write(JSONSerializer.toJSON(obj));  
    }  
      
    /** 
     * json string convert to xml string
     */  
    public static String json2xml(String jsonString){  
        XMLSerializer xmlSerializer = new XMLSerializer();  
        xmlSerializer.setTypeHintsEnabled(true);//是否保留元素型別標識,預設true
        xmlSerializer.setElementName("e");//設定元素標籤,預設e
        xmlSerializer.setArrayName("a");//設定陣列標籤,預設a
        xmlSerializer.setObjectName("o");//設定物件標籤,預設o
        return xmlSerializer.write(JSONSerializer.toJSON(jsonString));  
    }
	
}
都是些比較常見的轉換,寫的不是很全,基本夠用了,測試程式碼如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.ezmorph.test.ArrayAssertions;
import org.junit.Assert;
import org.junit.Test;

public class JsonLibUtilsTest {

	@Test
	public void pojo2json_test(){
		User user = new User(1, "張三");
		String json = JsonLibUtils.pojo2json(user);
		Assert.assertEquals("{\"id\":1,\"name\":\"張三\"}", json);
	}
	
	@Test
	public void object2json_test(){
		int[] intArray = new int[]{1,4,5};
		String json = JsonLibUtils.object2json(intArray);
		Assert.assertEquals("[1,4,5]", json);
		User user1 = new User(1,"張三");
		User user2 = new User(2,"李四");
		User[] userArray = new User[]{user1,user2};
		String json2 = JsonLibUtils.object2json(userArray);
		Assert.assertEquals("[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]", json2);
		List<User> userList = new ArrayList<>();
		userList.add(user1);
		userList.add(user2);
		String json3 = JsonLibUtils.object2json(userList);
		Assert.assertEquals("[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]", json3);
		//這裡的map的key必須為String型別
		Map<String,Object> map = new HashMap<>();
		map.put("id", 1);
		map.put("name", "張三");
		String json4 = JsonLibUtils.object2json(map);
		Assert.assertEquals("{\"id\":1,\"name\":\"張三\"}", json4);
		Map<String,User> map2 = new HashMap<>();
		map2.put("user1", user1);
		map2.put("user2", user2);
		String json5 = JsonLibUtils.object2json(map2);
		Assert.assertEquals("{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"張三\"}}", json5);
	}
	
	@Test
	public void xml2json_test(){
		String xml1 = "<User><id>1</id><name>張三</name></User>";
		String json = JsonLibUtils.xml2json(xml1);
		Assert.assertEquals("{\"id\":\"1\",\"name\":\"張三\"}", json);
		String xml2 = "<Response><CustID>1300000428</CustID><Items><Item><Sku_ProductNo>sku_0004</Sku_ProductNo></Item><Item><Sku_ProductNo>0005</Sku_ProductNo></Item></Items></Response>";
		String json2 = JsonLibUtils.xml2json(xml2);
		//處理陣列時expected是處理結果,但不是我們想要的格式
		String expected = "{\"CustID\":\"1300000428\",\"Items\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"0005\"}]}";
		Assert.assertEquals(expected, json2);
		//實際上我們想要的是expected2這種格式,所以用json-lib來實現含有陣列的xml to json是不行的
		String expected2 = "{\"CustID\":\"1300000428\",\"Items\":{\"Item\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"0005\"}]}}";
		Assert.assertEquals(expected2, json2);
	}
	
	@Test
	public void json2arrays_test(){
		String json = "[\"張三\",\"李四\"]";
		Object[] array = JsonLibUtils.json2arrays(json);
		Object[] expected = new Object[] { "張三", "李四" };
		ArrayAssertions.assertEquals(expected, array);                                                                                            
		//無法將JSON字串轉換為物件陣列
		String json2 = "[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]";
		Object[] array2 = JsonLibUtils.json2arrays(json2);
		User user1 = new User(1,"張三");
		User user2 = new User(2,"李四");
		Object[] expected2 = new Object[] { user1, user2 };
		ArrayAssertions.assertEquals(expected2, array2);
	}
	
	@Test
	public void json2list_test(){
		String json = "[\"張三\",\"李四\"]";
		List<String> list = JsonLibUtils.json2list(json, String.class);
		Assert.assertTrue(list.size()==2&&list.get(0).equals("張三")&&list.get(1).equals("李四"));
		String json2 = "[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]";
		List<User> list2 = JsonLibUtils.json2list(json2, User.class);
		Assert.assertTrue(list2.size()==2&&list2.get(0).getId()==1&&list2.get(1).getId()==2);
	}
	
	@Test
	public void json2pojo_test(){
		String json = "{\"id\":1,\"name\":\"張三\"}";
		User user = (User) JsonLibUtils.json2pojo(json, User.class);
		Assert.assertEquals(json, user.toString());
	}
	
	@Test
	public void json2map_test(){
		String json = "{\"id\":1,\"name\":\"張三\"}";
		Map map = JsonLibUtils.json2map(json);
		int id = Integer.parseInt(map.get("id").toString());
		String name = map.get("name").toString();
		System.out.println(name);
		Assert.assertTrue(id==1&&name.equals("張三"));
		String json2 = "{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"張三\"}}";
		Map map2 = JsonLibUtils.json2map(json2, User.class);
		System.out.println(map2);
	}
	
	@Test
	public void json2xml_test(){
		String json = "{\"id\":1,\"name\":\"張三\"}";
		String xml = JsonLibUtils.json2xml(json);
		Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<o><id type=\"number\">1</id><name type=\"string\">張三</name></o>\r\n", xml);
		System.out.println(xml);
		String json2 = "[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]";
		String xml2 = JsonLibUtils.json2xml(json2);
		System.out.println(xml2);
		Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<a><e class=\"object\"><id type=\"number\">1</id><name type=\"string\">張三</name></e><e class=\"object\"><id type=\"number\">2</id><name type=\"string\">李四</name></e></a>\r\n", xml2);
	}
	
	public static class User{
		private int id;
		private String name;
		
		public User() {
		}
		public User(int id, String name) {
			this.id = id;
			this.name = name;
		}
		@Override
		public String toString() {
			return "{\"id\":"+id+",\"name\":\""+name+"\"}";
		}
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}
}
json-lib在XML轉換為JSON在有陣列的情況下會有問題,還有在JSON轉換為XML時都會有元素標識如<o><a><e>等,在一般情況下我們可能都不需要,暫時還不知道如何過濾這些元素名稱。

因為json-lib的種種缺點,基本停止了更新,也不支援註解轉換,後來便有了jackson流行起來,它比json-lib的轉換效率要高很多,依賴很少,社群也比較活躍,它分為3個部分:

Streaming (docs) ("jackson-core") defines low-level streaming API, and includes JSON-specific implementations
Annotations (docs) ("jackson-annotations") contains standard Jackson annotations
Databind (docs) ("jackson-databind") implements data-binding (and object serialization) support on streaming package; it depends both on streaming and annotations packages
我們依舊開始上程式碼,首先是它的依賴:
  	<!-- for jackson -->
	<dependency>
	  	<groupId>com.fasterxml.jackson.dataformat</groupId>
	  	<artifactId>jackson-dataformat-xml</artifactId>
	  	<version>2.1.3</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.1.3</version>
		<type>java-source</type>
		<scope>compile</scope>
	</dependency>
這裡我要說下,有很多基於jackson的工具,大家可以按照自己的實際需求來需找對應的依賴,我這裡為了方便轉換xml所以用了dataformat-xml和databind

使用jackson實現多種轉換:

package cn.yangyong.fodder.util;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

/**
 * jsonson utils
 * @see http://jackson.codehaus.org/
 * @see https://github.com/FasterXML/jackson
 * @see http://wiki.fasterxml.com/JacksonHome
 * @author magic_yy
 *
 */
public class JacksonUtils {
	
	private static ObjectMapper objectMapper = new ObjectMapper();
	private static XmlMapper xmlMapper = new XmlMapper();
	
	/**
	 * javaBean,list,array convert to json string
	 */
	public static String obj2json(Object obj) throws Exception{
		return objectMapper.writeValueAsString(obj);
	}
	
	/**
	 * json string convert to javaBean
	 */
	public static <T> T json2pojo(String jsonStr,Class<T> clazz) throws Exception{
		return objectMapper.readValue(jsonStr, clazz);
	}
	
	/**
	 * json string convert to map
	 */
	public static <T> Map<String,Object> json2map(String jsonStr)throws Exception{
		return objectMapper.readValue(jsonStr, Map.class);
	}
	
	/**
	 * json string convert to map with javaBean
	 */
	public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz)throws Exception{
		Map<String,Map<String,Object>> map =  objectMapper.readValue(jsonStr, new TypeReference<Map<String,T>>() {
		});
		Map<String,T> result = new HashMap<String, T>();
		for (Entry<String, Map<String,Object>> entry : map.entrySet()) {
			result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));
		}
		return result;
	}
	
	/**
	 * json array string convert to list with javaBean
	 */
	public static <T> List<T> json2list(String jsonArrayStr,Class<T> clazz)throws Exception{
		List<Map<String,Object>> list = objectMapper.readValue(jsonArrayStr, new TypeReference<List<T>>() {
		});
		List<T> result = new ArrayList<>();
		for (Map<String, Object> map : list) {
			result.add(map2pojo(map, clazz));
		}
		return result;
	}
	
	/**
	 * map convert to javaBean
	 */
	public static <T> T map2pojo(Map map,Class<T> clazz){
		return objectMapper.convertValue(map, clazz);
	}
	
	/**
	 * json string convert to xml string
	 */
	public static String json2xml(String jsonStr)throws Exception{
		JsonNode root = objectMapper.readTree(jsonStr);
		String xml = xmlMapper.writeValueAsString(root);
		return xml;
	}
	
	/**
	 * xml string convert to json string
	 */
	public static String xml2json(String xml)throws Exception{
		StringWriter w = new StringWriter();
        JsonParser jp = xmlMapper.getFactory().createParser(xml);
        JsonGenerator jg = objectMapper.getFactory().createGenerator(w);
        while (jp.nextToken() != null) {
            jg.copyCurrentEvent(jp);
        }
        jp.close();
        jg.close();
        return w.toString();
	}
	
}
只用了其中的一部分功能,有關annotation部分因為從沒用到所以沒寫,大家可以自行研究下,我這裡就不提了。jackson的測試程式碼如下:
package cn.yangyong.fodder.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import cn.yangyong.fodder.util.JacksonUtils;

public class JacksonUtilsTest {

	@Test
	public void test_pojo2json() throws Exception{
		String json = JacksonUtils.obj2json(new User(1, "張三"));
		Assert.assertEquals("{\"id\":1,\"name\":\"張三\"}", json);
		List<User> list = new ArrayList<>();
		list.add(new User(1, "張三"));
		list.add(new User(2, "李四"));
		String json2 = JacksonUtils.obj2json(list);
		Assert.assertEquals("[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]", json2);
		Map<String,User> map = new HashMap<>();
		map.put("user1", new User(1, "張三"));
		map.put("user2", new User(2, "李四"));
		String json3 = JacksonUtils.obj2json(map);
		Assert.assertEquals("{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"張三\"}}", json3);
	}
	
	@Test
	public void test_json2pojo() throws Exception{
		String json = "{\"id\":1,\"name\":\"張三\"}";
		User user = JacksonUtils.json2pojo(json, User.class);
		Assert.assertTrue(user.getId()==1&&user.getName().equals("張三"));
	}
	
	@Test
	public void test_json2map() throws Exception{
		String json = "{\"id\":1,\"name\":\"張三\"}";
		Map<String,Object> map = JacksonUtils.json2map(json);
		Assert.assertEquals("{id=1, name=張三}", map.toString());
		String json2 = "{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"張三\"}}";
		Map<String,User> map2 = JacksonUtils.json2map(json2, User.class);
		User user1 = map2.get("user1");
		User user2 = map2.get("user2");
		Assert.assertTrue(user1.getId()==1&&user1.getName().equals("張三"));
		Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));
	}
	
	@Test
	public void test_json2list() throws Exception{
		String json = "[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]";
		List<User> list = JacksonUtils.json2list(json,User.class);
		User user1 = list.get(0);
		User user2 = list.get(1);
		Assert.assertTrue(user1.getId()==1&&user1.getName().equals("張三"));
		Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));
	}
	
	@Test
	public void test_map2pojo(){
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("id", 1);
		map.put("name", "張三");
		User user = JacksonUtils.map2pojo(map, User.class);
		Assert.assertTrue(user.getId()==1&&user.getName().equals("張三"));
		System.out.println(user);
	}
	
	@Test
	public void test_json2xml() throws Exception{
		String json = "{\"id\":1,\"name\":\"張三\"}";
		String xml = JacksonUtils.json2xml(json);
		Assert.assertEquals("<ObjectNode xmlns=\"\"><id>1</id><name>張三</name></ObjectNode>", xml);
		String json2 = "{\"Items\":{\"RequestInterfaceSku\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"sku_0005\"}]}}";
		String xml2 = JacksonUtils.json2xml(json2);
		Assert.assertEquals("<ObjectNode xmlns=\"\"><Items><RequestInterfaceSku><Sku_ProductNo>sku_0004</Sku_ProductNo></RequestInterfaceSku><RequestInterfaceSku><Sku_ProductNo>sku_0005</Sku_ProductNo></RequestInterfaceSku></Items></ObjectNode>", xml2);
	}
	
	@Test
	public void test_xml2json() throws Exception{
		String xml = "<ObjectNode xmlns=\"\"><id>1</id><name>張三</name></ObjectNode>";
		String json = JacksonUtils.xml2json(xml);
		Assert.assertEquals("{\"id\":1,\"name\":\"張三\"}", json);
		String xml2 = "<ObjectNode xmlns=\"\"><Items><RequestInterfaceSku><Sku_ProductNo>sku_0004</Sku_ProductNo></RequestInterfaceSku><RequestInterfaceSku><Sku_ProductNo>sku_0005</Sku_ProductNo></RequestInterfaceSku></Items></ObjectNode>";
		String json2 = JacksonUtils.xml2json(xml2);
		//expected2是我們想要的格式,但實際結果確實expected1,所以用jackson實現xml直接轉換為json在遇到陣列時是不可行的
		String expected1 = "{\"Items\":{\"RequestInterfaceSku\":{\"Sku_ProductNo\":\"sku_0004\"},\"RequestInterfaceSku\":{\"Sku_ProductNo\":\"sku_0005\"}}}";
		String expected2 = "{\"Items\":{\"RequestInterfaceSku\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"sku_0005\"}]}}";
		Assert.assertEquals(expected1, json2);
		Assert.assertEquals(expected2, json2);
	}
	
	private static class User{
		private int id;
		private String name; 
		
		public User() {
		}
		public User(int id, String name) {
			this.id = id;
			this.name = name;
		}
		@Override
		public String toString() {
			return "{\"id\":"+id+",\"name\":\""+name+"\"}";
		}
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}
}
測試後發現xml轉換為json時也有問題,居然不認識陣列,真是悲劇。好吧就由它吧,也可能是我的方法不正確。


jackson一直很主流,社群和文件支援也很充足,但有人還是嫌它不夠快,不夠簡潔,於是便有了fastjson,看名字就知道它的主要特點就是快,可能在功能和其他支援方面不能和jackson媲美,但天下武功,唯快不破,這就決定了fastjson有了一定的市場。不解釋,直接上程式碼。

	<!-- for fastjson -->
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.1.33</version>
	</dependency>
沃,除了自身零依賴,再看它的API使用。
使用fastjson實現多種轉換:
package cn.yangyong.fodder.util;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

/**
 * fastjson utils
 * 
 * @author magic_yy
 * @see https://github.com/alibaba/fastjson
 * @see http://code.alibabatech.com/wiki/display/FastJSON
 */
public class FastJsonUtils {
	
	private static SerializeConfig mapping = new SerializeConfig();
	
	static{
		mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
	}
	
	/**
	 * javaBean、list、map convert to json string
	 */
	public static String obj2json(Object obj){
//		return JSON.toJSONString(obj,SerializerFeature.UseSingleQuotes);//使用單引號
//		return JSON.toJSONString(obj,true);//格式化資料,方便閱讀
		return JSON.toJSONString(obj,mapping);
	}
	
	/**
	 * json string convert to javaBean、map
	 */
	public static <T> T json2obj(String jsonStr,Class<T> clazz){
		return JSON.parseObject(jsonStr,clazz);
	}
	
	/**
	 * json array string convert to list with javaBean
	 */
	public static <T> List<T> json2list(String jsonArrayStr,Class<T> clazz){
		return JSON.parseArray(jsonArrayStr, clazz);
	}
	
	/**
	 * json string convert to map
	 */
	public static <T> Map<String,Object> json2map(String jsonStr){
		return json2obj(jsonStr, Map.class);
	}
	
	/**
	 * json string convert to map with javaBean
	 */
	public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz){
		Map<String,T> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, T>>() {});
		for (Entry<String, T> entry : map.entrySet()) {
			JSONObject obj = (JSONObject) entry.getValue();
			map.put(entry.getKey(), JSONObject.toJavaObject(obj, clazz));
		}
		return map;
	}
}
API真的很簡潔,很方便,這裡依舊只用了部分功能,關於註解部分請大家自行研究。測試程式碼如下:
package cn.yangyong.fodder.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

public class FastJsonTest {
	
	@Test
	public void test_dateFormat(){
		Date date = new Date();
		String json = FastJsonUtils.obj2json(date);
		String expected = "\""+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)+"\"";
		Assert.assertEquals(expected, json);
	}
	
	@Test
	public void test_obj2json(){
		User user = new User(1, "張三");
		String json = FastJsonUtils.obj2json(user);
		Assert.assertEquals("{\"id\":1,\"name\":\"張三\"}", json);
		List<User> list = new ArrayList<>();
		list.add(new User(1, "張三"));
		list.add(new User(2, "李四"));
		String json2 = FastJsonUtils.obj2json(list);
		Assert.assertEquals("[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]", json2);
		Map<String,User> map = new HashMap<>();
		map.put("user1", new User(1, "張三"));
		map.put("user2", new User(2, "李四"));
		String json3 = FastJsonUtils.obj2json(map);
		Assert.assertEquals("{\"user1\":{\"id\":1,\"name\":\"張三\"},\"user2\":{\"id\":2,\"name\":\"李四\"}}", json3);
	}
	
	@Test
	public void test_json2obj(){
		String json = "{\"id\":1,\"name\":\"張三\"}";
		User user = FastJsonUtils.json2obj(json, User.class);
		Assert.assertTrue(user.getId()==1&&user.getName().equals("張三"));
	}
	
	@Test
	public void test_json2list(){
		String json = "[{\"id\":1,\"name\":\"張三\"},{\"id\":2,\"name\":\"李四\"}]";
		List<User> list = FastJsonUtils.json2list(json, User.class);
		User user1 = list.get(0);
		User user2 = list.get(1);
		Assert.assertTrue(user1.getId()==1&&user1.getName().equals("張三"));
		Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));
	}
	
	@Test
	public void test_json2map() throws Exception{
		String json = "{\"id\":1,\"name\":\"張三\"}";
		Map<String,Object> map = FastJsonUtils.json2map(json);
		Assert.assertEquals("{id=1, name=張三}", map.toString());
		String json2 = "{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"張三\"}}";
		Map<String,User> map2 = FastJsonUtils.json2map(json2, User.class);
		User user1 = map2.get("user1");
		User user2 = map2.get("user2");
		Assert.assertTrue(user1.getId()==1&&user1.getName().equals("張三"));
		Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));
	}
	
	private static class User{
		private int id;
		private String name; 
		
		public User() {
		}
		public User(int id, String name) {
			this.id = id;
			this.name = name;
		}
		@Override
		public String toString() {
			return "{\"id\":"+id+",\"name\":\""+name+"\"}";
		}
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}
	
}
只有json和javaBean直接的相互轉換,沒有xml的轉換,真可惜。好吧,誰叫人家定位不一樣呢,要想功能全還是用jackson吧。

最後給大家介紹下json和xml之間不依賴javaBean直接相互轉換的工具staxon,相比很多時候大家都想動態的將json和xml相互轉換卻不依賴其他javaBean,自己寫真的是很麻煩,要人命,用jackson等其他轉換工具時結果都不是我想要的

比如有下面xml和json,他們是等價的:

<Response>
	<CustID>1300000428</CustID>
	<CompID>1100000324</CompID>
	<Items>
		<Item>
			<Sku_ProductNo>sku_0004</Sku_ProductNo>
			<Wms_Code>1700386977</Wms_Code>
			<Sku_Response>T</Sku_Response>
			<Sku_Reason></Sku_Reason>
		</Item>
		<Item>
			<Sku_ProductNo>0005</Sku_ProductNo>
			<Wms_Code>1700386978</Wms_Code>
			<Sku_Response>T</Sku_Response>
			<Sku_Reason></Sku_Reason>
		</Item>
	</Items>
</Response>
{
	"Response" : {
		"CustID" : 1300000428,
		"CompID" : 1100000324,
		"Items" : {
			"Item" : [ {
				"Sku_ProductNo" : "sku_0004",
				"Wms_Code" : 1700386977,
				"Sku_Response" : "T",
				"Sku_Reason" : null
			}, {
				"Sku_ProductNo" : "0005",
				"Wms_Code" : 1700386978,
				"Sku_Response" : "T",
				"Sku_Reason" : null
			} ]
		}
	}
}
下面我們使用staxon來實現上面2種互轉
        <!-- for staxon -->
	<dependency>
		<groupId>de.odysseus.staxon</groupId>
		<artifactId>staxon</artifactId>
		<version>1.2</version>
	</dependency>
嗯,沒有第三方依賴,上轉換程式碼:
package cn.yangyong.fodder.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;

import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.json.JsonXMLOutputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;

/**
 * json and xml converter
 * @author magic_yy
 * @see https://github.com/beckchr/staxon
 * @see https://github.com/beckchr/staxon/wiki
 *
 */
public class StaxonUtils {
	
	/**
	 * json string convert to xml string
	 */
	public static String json2xml(String json){
		StringReader input = new StringReader(json);
		StringWriter output = new StringWriter();
		JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
		try {
			XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
			XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
			writer = new PrettyXMLEventWriter(writer);
			writer.add(reader);
			reader.close();
			writer.close();
		} catch( Exception e){
			e.printStackTrace();
		} finally {
			try {
				output.close();
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(output.toString().length()>=38){//remove <?xml version="1.0" encoding="UTF-8"?>
			return output.toString().substring(39);
		}
		return output.toString();
	}
	
	/**
	 * xml string convert to json string
	 */
	public static String xml2json(String xml){
		StringReader input = new StringReader(xml);
		StringWriter output = new StringWriter();
		JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(true).prettyPrint(true).build();
		try {
			XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
			XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
			writer.add(reader);
			reader.close();
			writer.close();
		} catch( Exception e){
			e.printStackTrace();
		} finally {
			try {
				output.close();
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return output.toString();
	}
}
當然,這裡我也就只用到了它的部分功能,最主要的還是json和xml直接的轉換了撒。其他功能自己看咯,不多做介紹了。測試程式碼如下:
package cn.yangyong.fodder.util;

import org.junit.Test;

public class StaxonUtilsTest {
	
	@Test
	public void test_json2xml(){
		String json = "{\"Response\" : {\"CustID\" : 1300000428,\"CompID\" : 1100000324,\"Items\" : {\"Item\" : [ {\"Sku_ProductNo\" : \"sku_0004\",\"Wms_Code\" : 1700386977,\"Sku_Response\" : \"T\",\"Sku_Reason\" : null}, {\"Sku_ProductNo\" : \"0005\",\"Wms_Code\" : 1700386978,\"Sku_Response\" : \"T\",\"Sku_Reason\" : null}]}}}";
		String xml = StaxonUtils.json2xml(json);
		System.out.println(xml);
	}
	
	@Test
	public void test_xml2json(){
		String xml = "<Response><CustID>1300000428</CustID><CompID>1100000324</CompID><Items><Item><Sku_ProductNo>sku_0004</Sku_ProductNo><Wms_Code>1700386977</Wms_Code><Sku_Response>T</Sku_Response><Sku_Reason></Sku_Reason></Item><Item><Sku_ProductNo>0005</Sku_ProductNo><Wms_Code>1700386978</Wms_Code><Sku_Response>T</Sku_Response><Sku_Reason></Sku_Reason></Item></Items></Response>";
		String json = StaxonUtils.xml2json(xml);
		System.out.println(json);
	}
}

哦了,就說到這裡吧,這幾個都研究不深,當工具來用,僅供參考。




相關推薦

jsonjavaBeanxml工具介紹

工作中經常要用到Json、JavaBean、Xml之間的相互轉換,用到了很多種方式,這裡做下總結,以供參考。 現在主流的轉換工具有json-lib、jackson、fastjson等,我為大家一一做簡單介紹,主要還是以程式碼形式貼出如何簡單應用這些工具的,更多高階功能還需大

序列化與JavaBeanxml

序列化和反序列化: 一、序列化和反序列化的概念   把物件轉換為位元組序列的過程稱為物件的序列化。   把位元組序列恢復為物件的過程稱為物件的反序列化。   物件的序列化主要有兩種用途:   1) 把物件的位元組序列永久地儲存到硬碟上,通常存放在一

jsonjavaBeanxml工具

      工作中經常要用到Json、JavaBean、Xml之間的相互轉換,用到了很多種方式,這裡做下總結,以供參考。  現在主流的轉換工具有json-lib、jackson、fastjson等,我為大家一一做簡單介紹,主要還是以程式碼形式貼出如何簡單應用這些工具的,更多高

JAVA-JSONXML-【粗暴應用分享】

其實很多時候,我們只需要魚,而不是漁,吶,給你魚。 在平時的開發中,有時候會用到JSON和XML的互轉 - net.sf.json-lib.json-lib包提供一些互轉的方法; - com.alibaba.fastjson並沒有提供; 但是

Spring日記_02之 jsonjavaBean.doMySqlMyBatis 環境搭建結束

JSON Json是JavaScript直接量語法   無參構造方法直接 Alt + \ 就可以提示新增 Project – Clean 瀏覽器向伺服器傳送請求,伺服器中的Spring中的SpringMVC將Json字串傳送到客戶端瀏覽器,瀏覽器的jquery解析JSON字串成為J

TMemoryStreamString與OleVariant

//////////////////////////////////////////////////////////////////////////////// //功能: STRING 的內容流化到 OLEVARIANT 中 //引數: /////////////////////////////

ListDataTable和物件,ListDataTable異常Nullable解決方案

using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace ClassLibrary1 { public class D

jsonxml

一、簡介 本文介紹json串與xml串相互轉換的一種方式。 二、開發步驟 1、新增maven依賴 <dependency> <groupId>org.json<

JS實現xmljson(也可看做物件)

最近有個前端的需求: 解析後臺xml, 並新增刪除和修改, 然後傳給後臺, 思來想去, 最簡單的辦法就是利用xml和物件互轉, 即從後臺讀取xml傳到前臺並形成表格(已有程式碼,或者用物件生成表格), 前臺可編輯表格(包括新增,刪除),提交時將表格資料存入物件中

java實現具有相同屬性名稱及相似型別的pojodtovo等的

  已應用於實際專案:1.thrift物件與dto之間的互轉                                       2.pojo與dto之間的互轉                                       3.pojo與vo之間的互轉

SimpleDateFormatDate和String

imp 容易 小寫 格式 原因 string str -m date 今天在修改bug時遇到一個查詢異常:根據時間段查詢的時候,如果查詢時間段含12點鐘,那麽能查到時間段之外的其他數據; 跟蹤了數據流動發現,前同事寫的程序中,有一處是講前端傳來時間字符串轉為Date的一種時

Java8 LocalDateTime獲取時間戳(毫秒/秒)LocalDateTime與StringDate與LocalDateTime

本文目前提供:LocalDateTime獲取時間戳(毫秒/秒)、LocalDateTime與String互轉、Date與LocalDateTime互轉 文中都使用的時區都是東8區,也就是北京時間。這是為了防止伺服器設定時區錯誤時導致時間不對,如果您是其他時區,請自行修改

.NET base64與檔案方法 byte[]與檔案方法

base64與檔案互轉 /// <summary> /// 檔案轉換成Base64字串 /// </summary> /// <param name="fileName">檔案絕對路徑<

js陣列物件與字串

JSON.stringify 函式:陣列(物件)/物件轉化為字串 語法 JSON.stringify(obj/Array [, replacer] [, space]) 示例1 此示例使用 JSON.stringify 將 contact 物件轉換為 J

各種概念POJOJAVABEANDAODTOPOVOBOSSHEJB

簡單 cts 取數據 bean strong 方式 不同的應用 enter 合規 轉自:https://my.oschina.net/pacoyang/blog/151695 POJO(pure old java object)是普通java類,有一些private的參數作

Json對象與Json字符串(4轉換方式)

pan cnblogs 方法 () stringify for ie7 afa .json 1>jQuery插件支持的轉換方式 $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以將json字符串轉換成json

JAVA bean與XML的利器---XStream

pub 普通 ati mat his cit true 是我 package 最近在項目中遇到了JAVA bean 和XML互轉的需求, 本來準備循規蹈矩使用dom4j忽然想起來之前曾接觸過的XStream, 一番研究豁然開朗,利器啊利器, 下來就XStream的一些用法與

php數組與xml

php數組與xml互轉類代碼: /** * @desc:xml與array互轉 * @author [Lee] <[<[email protected]>]> * @property * data 傳入的數據 * @method * arraytoxml 數組轉xml

java物件與XML

1. 定義XML對應的java實體類(可巢狀) import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorT

jackson完成json和物件/map/list

jackson是一款非常好用的json轉換工具,總結一下具體用法   一:匯入依賴   <dependency>     <groupId>com.fasterxml.jackson.core</grou