轉載至:http://blog.csdn.net/sdyy321/article/details/7024236java
工做中常常要用到Json、JavaBean、Xml之間的相互轉換,用到了不少種方式,這裏作下總結,以供參考。git
如今主流的轉換工具備json-lib、jackson、fastjson等,我爲你們一一作簡單介紹,主要仍是以代碼形式貼出如何簡單應用這些工具的,更多高級功能還需你們深刻研究。github
首先是json-lib,算是很早的轉換工具了,用的人不少,說實在如今徹底不適合了,缺點比較多,依賴的第三方實在是比較多,效率低下,API也比較繁瑣,說他純粹是由於之前的老項目不少人都用到它。不廢話,開始上代碼。json
須要的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實現多種轉換app
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)); } }
都是些比較常見的轉換,寫的不是很全,基本夠用了,測試代碼以下:maven
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>等,在通常狀況下咱們可能都不須要,暫時還不知道如何過濾這些元素名稱。ide
由於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); } }
哦了,就說到這裏吧,這幾個都研究不深,當工具來用,僅供參考。