• json、javaBean、xml互转的几种工具介绍 (转载)


    工作中经常要用到Json、JavaBean、Xml之间的相互转换,用到了很多种方式,这里做下总结,以供参考。

    现在主流的转换工具有json-lib、jackson、fastjson等,我为大家一一做简单介绍,主要还是以代码形式贴出如何简单应用这些工具的,更多高级功能还需大家深入研究。

    首先是json-lib,算是很早的转换工具了,用的人很多,说实在现在完全不适合了,缺点比较多,依赖的第三方实在是比较多,效率低下,API也比较繁琐,说他纯粹是因为以前的老项目很多人都用到它。不废话,开始上代码。

    需要的maven依赖:

    [plain] view plaincopy
     
    1. <!-- for json-lib -->  
    2. <dependency>    
    3.     <groupId>net.sf.json-lib</groupId>    
    4.     <artifactId>json-lib</artifactId>    
    5.     <version>2.4</version>    
    6.     <classifier>jdk15</classifier>    
    7. </dependency>  
    8. <dependency>  
    9.     <groupId>xom</groupId>  
    10.     <artifactId>xom</artifactId>  
    11.     <version>1.1</version>  
    12. </dependency>   
    13. <dependency>  
    14.     <groupId>xalan</groupId>  
    15.     <artifactId>xalan</artifactId>  
    16.     <version>2.7.1</version>  
    17. </dependency>  


    使用json-lib实现多种转换

    [java] view plaincopy
     
    1. import java.text.SimpleDateFormat;  
    2. import java.util.Date;  
    3. import java.util.HashMap;  
    4. import java.util.List;  
    5. import java.util.Map;  
    6. import java.util.Map.Entry;  
    7. import javax.swing.text.Document;  
    8. import net.sf.ezmorph.Morpher;  
    9. import net.sf.ezmorph.MorpherRegistry;  
    10. import net.sf.ezmorph.bean.BeanMorpher;  
    11. import net.sf.ezmorph.object.DateMorpher;  
    12. import net.sf.json.JSON;  
    13. import net.sf.json.JSONArray;  
    14. import net.sf.json.JSONObject;  
    15. import net.sf.json.JSONSerializer;  
    16. import net.sf.json.JsonConfig;  
    17. import net.sf.json.processors.JsonValueProcessor;  
    18. import net.sf.json.util.CycleDetectionStrategy;  
    19. import net.sf.json.util.JSONUtils;  
    20. import net.sf.json.xml.XMLSerializer;  
    21.   
    22. /** 
    23.  * json-lib utils 
    24.  * @author magic_yy 
    25.  * @see json-lib.sourceforge.net/ 
    26.  * @see https://github.com/aalmiray/Json-lib 
    27.  * 
    28.  */  
    29. public class JsonLibUtils {  
    30.       
    31.     public static JsonConfig config = new JsonConfig();  
    32.       
    33.     static{  
    34.         config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);//忽略循环,避免死循环  
    35.         config.registerJsonValueProcessor(Date.classnew JsonValueProcessor() {//处理Date日期转换  
    36.             @Override  
    37.             public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {  
    38.                  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    39.                     Date d=(Date) arg1;  
    40.                     return sdf.format(d);  
    41.             }  
    42.             @Override  
    43.             public Object processArrayValue(Object arg0, JsonConfig arg1) {  
    44.                 return null;  
    45.             }  
    46.         });  
    47.     }  
    48.       
    49.     /**  
    50.      * java object convert to json string 
    51.      */    
    52.     public static String pojo2json(Object obj){  
    53.         return JSONObject.fromObject(obj,config).toString();//可以用toString(1)来实现格式化,便于阅读    
    54.     }    
    55.         
    56.     /**  
    57.      * array、map、Javabean convert to json string 
    58.      */    
    59.     public static String object2json(Object obj){    
    60.         return JSONSerializer.toJSON(obj).toString();    
    61.     }    
    62.         
    63.     /**  
    64.      * xml string convert to json string 
    65.      */    
    66.     public static String xml2json(String xmlString){    
    67.         XMLSerializer xmlSerializer = new XMLSerializer();    
    68.         JSON json = xmlSerializer.read(xmlString);    
    69.         return json.toString();    
    70.     }    
    71.         
    72.     /**  
    73.      * xml document convert to json string 
    74.      */    
    75.     public static String xml2json(Document xmlDocument){    
    76.         return xml2json(xmlDocument.toString());    
    77.     }    
    78.         
    79.     /**  
    80.      * json string convert to javaBean 
    81.      * @param <T> 
    82.      */    
    83.     @SuppressWarnings("unchecked")  
    84.     public static <T> T json2pojo(String jsonStr,Class<T> clazz){    
    85.         JSONObject jsonObj = JSONObject.fromObject(jsonStr);    
    86.         T obj = (T) JSONObject.toBean(jsonObj, clazz);    
    87.         return obj;    
    88.     }  
    89.       
    90.     /** 
    91.      * json string convert to map 
    92.      */  
    93.     public static Map<String,Object> json2map(String jsonStr){  
    94.         JSONObject jsonObj = JSONObject.fromObject(jsonStr);  
    95.         Map<String,Object> result = (Map<String, Object>) JSONObject.toBean(jsonObj, Map.class);  
    96.         return result;  
    97.     }  
    98.       
    99.     /** 
    100.      * json string convert to map with javaBean 
    101.      */  
    102.     public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz){  
    103.         JSONObject jsonObj = JSONObject.fromObject(jsonStr);  
    104.         Map<String,T> map = new HashMap<String, T>();  
    105.         Map<String,T> result = (Map<String, T>) JSONObject.toBean(jsonObj, Map.class, map);  
    106.         MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();  
    107.         Morpher dynaMorpher = new BeanMorpher(clazz,morpherRegistry);  
    108.         morpherRegistry.registerMorpher(dynaMorpher);  
    109.         morpherRegistry.registerMorpher(new DateMorpher(new String[]{ "yyyy-MM-dd HH:mm:ss" }));  
    110.         for (Entry<String,T> entry : result.entrySet()) {  
    111.             map.put(entry.getKey(), (T)morpherRegistry.morph(clazz, entry.getValue()));  
    112.         }  
    113.         return map;  
    114.     }  
    115.         
    116.     /**  
    117.      * json string convert to array 
    118.      */    
    119.     public static Object[] json2arrays(String jsonString) {    
    120.         JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(jsonString);  
    121. //      JSONArray jsonArray = JSONArray.fromObject(jsonString);    
    122.         JsonConfig jsonConfig = new JsonConfig();  
    123.         jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);  
    124.         Object[] objArray = (Object[]) JSONSerializer.toJava(jsonArray,jsonConfig);  
    125.         return objArray;  
    126.     }    
    127.         
    128.     /**  
    129.      * json string convert to list 
    130.      * @param <T> 
    131.      */    
    132.     @SuppressWarnings({ "unchecked""deprecation" })  
    133.     public static <T> List<T> json2list(String jsonString, Class<T> pojoClass){    
    134.         JSONArray jsonArray = JSONArray.fromObject(jsonString);    
    135.         return JSONArray.toList(jsonArray, pojoClass);  
    136.     }    
    137.         
    138.     /**  
    139.      * object convert to xml string 
    140.      */    
    141.     public static String obj2xml(Object obj){    
    142.         XMLSerializer xmlSerializer = new XMLSerializer();    
    143.         return xmlSerializer.write(JSONSerializer.toJSON(obj));    
    144.     }    
    145.         
    146.     /**  
    147.      * json string convert to xml string 
    148.      */    
    149.     public static String json2xml(String jsonString){    
    150.         XMLSerializer xmlSerializer = new XMLSerializer();    
    151.         xmlSerializer.setTypeHintsEnabled(true);//是否保留元素类型标识,默认true  
    152.         xmlSerializer.setElementName("e");//设置元素标签,默认e  
    153.         xmlSerializer.setArrayName("a");//设置数组标签,默认a  
    154.         xmlSerializer.setObjectName("o");//设置对象标签,默认o  
    155.         return xmlSerializer.write(JSONSerializer.toJSON(jsonString));    
    156.     }  
    157.       
    158. }  

    都是些比较常见的转换,写的不是很全,基本够用了,测试代码如下:

    [java] view plaincopy
     
    1. import java.util.ArrayList;  
    2. import java.util.HashMap;  
    3. import java.util.List;  
    4. import java.util.Map;  
    5. import net.sf.ezmorph.test.ArrayAssertions;  
    6. import org.junit.Assert;  
    7. import org.junit.Test;  
    8.   
    9. public class JsonLibUtilsTest {  
    10.   
    11.     @Test  
    12.     public void pojo2json_test(){  
    13.         User user = new User(1"张三");  
    14.         String json = JsonLibUtils.pojo2json(user);  
    15.         Assert.assertEquals("{"id":1,"name":"张三"}", json);  
    16.     }  
    17.       
    18.     @Test  
    19.     public void object2json_test(){  
    20.         int[] intArray = new int[]{1,4,5};  
    21.         String json = JsonLibUtils.object2json(intArray);  
    22.         Assert.assertEquals("[1,4,5]", json);  
    23.         User user1 = new User(1,"张三");  
    24.         User user2 = new User(2,"李四");  
    25.         User[] userArray = new User[]{user1,user2};  
    26.         String json2 = JsonLibUtils.object2json(userArray);  
    27.         Assert.assertEquals("[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]", json2);  
    28.         List<User> userList = new ArrayList<>();  
    29.         userList.add(user1);  
    30.         userList.add(user2);  
    31.         String json3 = JsonLibUtils.object2json(userList);  
    32.         Assert.assertEquals("[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]", json3);  
    33.         //这里的map的key必须为String类型  
    34.         Map<String,Object> map = new HashMap<>();  
    35.         map.put("id"1);  
    36.         map.put("name""张三");  
    37.         String json4 = JsonLibUtils.object2json(map);  
    38.         Assert.assertEquals("{"id":1,"name":"张三"}", json4);  
    39.         Map<String,User> map2 = new HashMap<>();  
    40.         map2.put("user1", user1);  
    41.         map2.put("user2", user2);  
    42.         String json5 = JsonLibUtils.object2json(map2);  
    43.         Assert.assertEquals("{"user2":{"id":2,"name":"李四"},"user1":{"id":1,"name":"张三"}}", json5);  
    44.     }  
    45.       
    46.     @Test  
    47.     public void xml2json_test(){  
    48.         String xml1 = "<User><id>1</id><name>张三</name></User>";  
    49.         String json = JsonLibUtils.xml2json(xml1);  
    50.         Assert.assertEquals("{"id":"1","name":"张三"}", json);  
    51.         String xml2 = "<Response><CustID>1300000428</CustID><Items><Item><Sku_ProductNo>sku_0004</Sku_ProductNo></Item><Item><Sku_ProductNo>0005</Sku_ProductNo></Item></Items></Response>";  
    52.         String json2 = JsonLibUtils.xml2json(xml2);  
    53.         //处理数组时expected是处理结果,但不是我们想要的格式  
    54.         String expected = "{"CustID":"1300000428","Items":[{"Sku_ProductNo":"sku_0004"},{"Sku_ProductNo":"0005"}]}";  
    55.         Assert.assertEquals(expected, json2);  
    56.         //实际上我们想要的是expected2这种格式,所以用json-lib来实现含有数组的xml to json是不行的  
    57.         String expected2 = "{"CustID":"1300000428","Items":{"Item":[{"Sku_ProductNo":"sku_0004"},{"Sku_ProductNo":"0005"}]}}";  
    58.         Assert.assertEquals(expected2, json2);  
    59.     }  
    60.       
    61.     @Test  
    62.     public void json2arrays_test(){  
    63.         String json = "["张三","李四"]";  
    64.         Object[] array = JsonLibUtils.json2arrays(json);  
    65.         Object[] expected = new Object[] { "张三""李四" };  
    66.         ArrayAssertions.assertEquals(expected, array);                                                                                              
    67.         //无法将JSON字符串转换为对象数组  
    68.         String json2 = "[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]";  
    69.         Object[] array2 = JsonLibUtils.json2arrays(json2);  
    70.         User user1 = new User(1,"张三");  
    71.         User user2 = new User(2,"李四");  
    72.         Object[] expected2 = new Object[] { user1, user2 };  
    73.         ArrayAssertions.assertEquals(expected2, array2);  
    74.     }  
    75.       
    76.     @Test  
    77.     public void json2list_test(){  
    78.         String json = "["张三","李四"]";  
    79.         List<String> list = JsonLibUtils.json2list(json, String.class);  
    80.         Assert.assertTrue(list.size()==2&&list.get(0).equals("张三")&&list.get(1).equals("李四"));  
    81.         String json2 = "[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]";  
    82.         List<User> list2 = JsonLibUtils.json2list(json2, User.class);  
    83.         Assert.assertTrue(list2.size()==2&&list2.get(0).getId()==1&&list2.get(1).getId()==2);  
    84.     }  
    85.       
    86.     @Test  
    87.     public void json2pojo_test(){  
    88.         String json = "{"id":1,"name":"张三"}";  
    89.         User user = (User) JsonLibUtils.json2pojo(json, User.class);  
    90.         Assert.assertEquals(json, user.toString());  
    91.     }  
    92.       
    93.     @Test  
    94.     public void json2map_test(){  
    95.         String json = "{"id":1,"name":"张三"}";  
    96.         Map map = JsonLibUtils.json2map(json);  
    97.         int id = Integer.parseInt(map.get("id").toString());  
    98.         String name = map.get("name").toString();  
    99.         System.out.println(name);  
    100.         Assert.assertTrue(id==1&&name.equals("张三"));  
    101.         String json2 = "{"user2":{"id":2,"name":"李四"},"user1":{"id":1,"name":"张三"}}";  
    102.         Map map2 = JsonLibUtils.json2map(json2, User.class);  
    103.         System.out.println(map2);  
    104.     }  
    105.       
    106.     @Test  
    107.     public void json2xml_test(){  
    108.         String json = "{"id":1,"name":"张三"}";  
    109.         String xml = JsonLibUtils.json2xml(json);  
    110.         Assert.assertEquals("<?xml version="1.0" encoding="UTF-8"?> <o><id type="number">1</id><name type="string">张三</name></o> ", xml);  
    111.         System.out.println(xml);  
    112.         String json2 = "[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]";  
    113.         String xml2 = JsonLibUtils.json2xml(json2);  
    114.         System.out.println(xml2);  
    115.         Assert.assertEquals("<?xml version="1.0" encoding="UTF-8"?> <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> ", xml2);  
    116.     }  
    117.       
    118.     public static class User{  
    119.         private int id;  
    120.         private String name;  
    121.           
    122.         public User() {  
    123.         }  
    124.         public User(int id, String name) {  
    125.             this.id = id;  
    126.             this.name = name;  
    127.         }  
    128.         @Override  
    129.         public String toString() {  
    130.             return "{"id":"+id+","name":""+name+""}";  
    131.         }  
    132.         public int getId() {  
    133.             return id;  
    134.         }  
    135.         public void setId(int id) {  
    136.             this.id = id;  
    137.         }  
    138.         public String getName() {  
    139.             return name;  
    140.         }  
    141.         public void setName(String name) {  
    142.             this.name = name;  
    143.         }  
    144.     }  
    145. }  

    json-lib在XML转换为JSON在有数组的情况下会有问题,还有在JSON转换为XML时都会有元素标识如<o><a><e>等,在一般情况下我们可能都不需要,暂时还不知道如何过滤这些元素名称。

    因为json-lib的种种缺点,基本停止了更新,也不支持注解转换,后来便有了jackson流行起来,它比json-lib的转换效率要高很多,依赖很少,社区也比较活跃,它分为3个部分:

    [plain] view plaincopy
     
    1. Streaming (docs) ("jackson-core") defines low-level streaming API, and includes JSON-specific implementations  
    2. Annotations (docs) ("jackson-annotations") contains standard Jackson annotations  
    3. Databind (docs) ("jackson-databind") implements data-binding (and object serialization) support on streaming package; it depends both on streaming and annotations packages  

    我们依旧开始上代码,首先是它的依赖:

    [plain] view plaincopy
     
    1.     <!-- for jackson -->  
    2. <dependency>  
    3.     <groupId>com.fasterxml.jackson.dataformat</groupId>  
    4.     <artifactId>jackson-dataformat-xml</artifactId>  
    5.     <version>2.1.3</version>  
    6. </dependency>  
    7. <dependency>  
    8.     <groupId>com.fasterxml.jackson.core</groupId>  
    9.     <artifactId>jackson-databind</artifactId>  
    10.     <version>2.1.3</version>  
    11.     <type>java-source</type>  
    12.     <scope>compile</scope>  
    13. </dependency>  

    这里我要说下,有很多基于jackson的工具,大家可以按照自己的实际需求来需找对应的依赖,我这里为了方便转换xml所以用了dataformat-xml和databind

    使用jackson实现多种转换:

    [java] view plaincopy
     
    1. package cn.yangyong.fodder.util;  
    2.   
    3. import java.io.StringWriter;  
    4. import java.util.ArrayList;  
    5. import java.util.HashMap;  
    6. import java.util.List;  
    7. import java.util.Map;  
    8. import java.util.Map.Entry;  
    9.   
    10. import com.fasterxml.jackson.core.JsonGenerator;  
    11. import com.fasterxml.jackson.core.JsonParser;  
    12. import com.fasterxml.jackson.core.type.TypeReference;  
    13. import com.fasterxml.jackson.databind.JsonNode;  
    14. import com.fasterxml.jackson.databind.ObjectMapper;  
    15. import com.fasterxml.jackson.dataformat.xml.XmlMapper;  
    16.   
    17. /** 
    18.  * jsonson utils 
    19.  * @see http://jackson.codehaus.org/ 
    20.  * @see https://github.com/FasterXML/jackson 
    21.  * @see http://wiki.fasterxml.com/JacksonHome 
    22.  * @author magic_yy 
    23.  * 
    24.  */  
    25. public class JacksonUtils {  
    26.       
    27.     private static ObjectMapper objectMapper = new ObjectMapper();  
    28.     private static XmlMapper xmlMapper = new XmlMapper();  
    29.       
    30.     /** 
    31.      * javaBean,list,array convert to json string 
    32.      */  
    33.     public static String obj2json(Object obj) throws Exception{  
    34.         return objectMapper.writeValueAsString(obj);  
    35.     }  
    36.       
    37.     /** 
    38.      * json string convert to javaBean 
    39.      */  
    40.     public static <T> T json2pojo(String jsonStr,Class<T> clazz) throws Exception{  
    41.         return objectMapper.readValue(jsonStr, clazz);  
    42.     }  
    43.       
    44.     /** 
    45.      * json string convert to map 
    46.      */  
    47.     public static <T> Map<String,Object> json2map(String jsonStr)throws Exception{  
    48.         return objectMapper.readValue(jsonStr, Map.class);  
    49.     }  
    50.       
    51.     /** 
    52.      * json string convert to map with javaBean 
    53.      */  
    54.     public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz)throws Exception{  
    55.         Map<String,Map<String,Object>> map =  objectMapper.readValue(jsonStr, new TypeReference<Map<String,T>>() {  
    56.         });  
    57.         Map<String,T> result = new HashMap<String, T>();  
    58.         for (Entry<String, Map<String,Object>> entry : map.entrySet()) {  
    59.             result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));  
    60.         }  
    61.         return result;  
    62.     }  
    63.       
    64.     /** 
    65.      * json array string convert to list with javaBean 
    66.      */  
    67.     public static <T> List<T> json2list(String jsonArrayStr,Class<T> clazz)throws Exception{  
    68.         List<Map<String,Object>> list = objectMapper.readValue(jsonArrayStr, new TypeReference<List<T>>() {  
    69.         });  
    70.         List<T> result = new ArrayList<>();  
    71.         for (Map<String, Object> map : list) {  
    72.             result.add(map2pojo(map, clazz));  
    73.         }  
    74.         return result;  
    75.     }  
    76.       
    77.     /** 
    78.      * map convert to javaBean 
    79.      */  
    80.     public static <T> T map2pojo(Map map,Class<T> clazz){  
    81.         return objectMapper.convertValue(map, clazz);  
    82.     }  
    83.       
    84.     /** 
    85.      * json string convert to xml string 
    86.      */  
    87.     public static String json2xml(String jsonStr)throws Exception{  
    88.         JsonNode root = objectMapper.readTree(jsonStr);  
    89.         String xml = xmlMapper.writeValueAsString(root);  
    90.         return xml;  
    91.     }  
    92.       
    93.     /** 
    94.      * xml string convert to json string 
    95.      */  
    96.     public static String xml2json(String xml)throws Exception{  
    97.         StringWriter w = new StringWriter();  
    98.         JsonParser jp = xmlMapper.getFactory().createParser(xml);  
    99.         JsonGenerator jg = objectMapper.getFactory().createGenerator(w);  
    100.         while (jp.nextToken() != null) {  
    101.             jg.copyCurrentEvent(jp);  
    102.         }  
    103.         jp.close();  
    104.         jg.close();  
    105.         return w.toString();  
    106.     }  
    107.       
    108. }  

    只用了其中的一部分功能,有关annotation部分因为从没用到所以没写,大家可以自行研究下,我这里就不提了。jackson的测试代码如下:

    [java] view plaincopy
     
    1. package cn.yangyong.fodder.util;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.HashMap;  
    5. import java.util.List;  
    6. import java.util.Map;  
    7. import org.junit.Assert;  
    8. import org.junit.Test;  
    9. import cn.yangyong.fodder.util.JacksonUtils;  
    10.   
    11. public class JacksonUtilsTest {  
    12.   
    13.     @Test  
    14.     public void test_pojo2json() throws Exception{  
    15.         String json = JacksonUtils.obj2json(new User(1"张三"));  
    16.         Assert.assertEquals("{"id":1,"name":"张三"}", json);  
    17.         List<User> list = new ArrayList<>();  
    18.         list.add(new User(1"张三"));  
    19.         list.add(new User(2"李四"));  
    20.         String json2 = JacksonUtils.obj2json(list);  
    21.         Assert.assertEquals("[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]", json2);  
    22.         Map<String,User> map = new HashMap<>();  
    23.         map.put("user1"new User(1"张三"));  
    24.         map.put("user2"new User(2"李四"));  
    25.         String json3 = JacksonUtils.obj2json(map);  
    26.         Assert.assertEquals("{"user2":{"id":2,"name":"李四"},"user1":{"id":1,"name":"张三"}}", json3);  
    27.     }  
    28.       
    29.     @Test  
    30.     public void test_json2pojo() throws Exception{  
    31.         String json = "{"id":1,"name":"张三"}";  
    32.         User user = JacksonUtils.json2pojo(json, User.class);  
    33.         Assert.assertTrue(user.getId()==1&&user.getName().equals("张三"));  
    34.     }  
    35.       
    36.     @Test  
    37.     public void test_json2map() throws Exception{  
    38.         String json = "{"id":1,"name":"张三"}";  
    39.         Map<String,Object> map = JacksonUtils.json2map(json);  
    40.         Assert.assertEquals("{id=1, name=张三}", map.toString());  
    41.         String json2 = "{"user2":{"id":2,"name":"李四"},"user1":{"id":1,"name":"张三"}}";  
    42.         Map<String,User> map2 = JacksonUtils.json2map(json2, User.class);  
    43.         User user1 = map2.get("user1");  
    44.         User user2 = map2.get("user2");  
    45.         Assert.assertTrue(user1.getId()==1&&user1.getName().equals("张三"));  
    46.         Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));  
    47.     }  
    48.       
    49.     @Test  
    50.     public void test_json2list() throws Exception{  
    51.         String json = "[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]";  
    52.         List<User> list = JacksonUtils.json2list(json,User.class);  
    53.         User user1 = list.get(0);  
    54.         User user2 = list.get(1);  
    55.         Assert.assertTrue(user1.getId()==1&&user1.getName().equals("张三"));  
    56.         Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));  
    57.     }  
    58.       
    59.     @Test  
    60.     public void test_map2pojo(){  
    61.         Map<String,Object> map = new HashMap<String, Object>();  
    62.         map.put("id"1);  
    63.         map.put("name""张三");  
    64.         User user = JacksonUtils.map2pojo(map, User.class);  
    65.         Assert.assertTrue(user.getId()==1&&user.getName().equals("张三"));  
    66.         System.out.println(user);  
    67.     }  
    68.       
    69.     @Test  
    70.     public void test_json2xml() throws Exception{  
    71.         String json = "{"id":1,"name":"张三"}";  
    72.         String xml = JacksonUtils.json2xml(json);  
    73.         Assert.assertEquals("<ObjectNode xmlns=""><id>1</id><name>张三</name></ObjectNode>", xml);  
    74.         String json2 = "{"Items":{"RequestInterfaceSku":[{"Sku_ProductNo":"sku_0004"},{"Sku_ProductNo":"sku_0005"}]}}";  
    75.         String xml2 = JacksonUtils.json2xml(json2);  
    76.         Assert.assertEquals("<ObjectNode xmlns=""><Items><RequestInterfaceSku><Sku_ProductNo>sku_0004</Sku_ProductNo></RequestInterfaceSku><RequestInterfaceSku><Sku_ProductNo>sku_0005</Sku_ProductNo></RequestInterfaceSku></Items></ObjectNode>", xml2);  
    77.     }  
    78.       
    79.     @Test  
    80.     public void test_xml2json() throws Exception{  
    81.         String xml = "<ObjectNode xmlns=""><id>1</id><name>张三</name></ObjectNode>";  
    82.         String json = JacksonUtils.xml2json(xml);  
    83.         Assert.assertEquals("{"id":1,"name":"张三"}", json);  
    84.         String xml2 = "<ObjectNode xmlns=""><Items><RequestInterfaceSku><Sku_ProductNo>sku_0004</Sku_ProductNo></RequestInterfaceSku><RequestInterfaceSku><Sku_ProductNo>sku_0005</Sku_ProductNo></RequestInterfaceSku></Items></ObjectNode>";  
    85.         String json2 = JacksonUtils.xml2json(xml2);  
    86.         //expected2是我们想要的格式,但实际结果确实expected1,所以用jackson实现xml直接转换为json在遇到数组时是不可行的  
    87.         String expected1 = "{"Items":{"RequestInterfaceSku":{"Sku_ProductNo":"sku_0004"},"RequestInterfaceSku":{"Sku_ProductNo":"sku_0005"}}}";  
    88.         String expected2 = "{"Items":{"RequestInterfaceSku":[{"Sku_ProductNo":"sku_0004"},{"Sku_ProductNo":"sku_0005"}]}}";  
    89.         Assert.assertEquals(expected1, json2);  
    90.         Assert.assertEquals(expected2, json2);  
    91.     }  
    92.       
    93.     private static class User{  
    94.         private int id;  
    95.         private String name;   
    96.           
    97.         public User() {  
    98.         }  
    99.         public User(int id, String name) {  
    100.             this.id = id;  
    101.             this.name = name;  
    102.         }  
    103.         @Override  
    104.         public String toString() {  
    105.             return "{"id":"+id+","name":""+name+""}";  
    106.         }  
    107.         public int getId() {  
    108.             return id;  
    109.         }  
    110.         public void setId(int id) {  
    111.             this.id = id;  
    112.         }  
    113.         public String getName() {  
    114.             return name;  
    115.         }  
    116.         public void setName(String name) {  
    117.             this.name = name;  
    118.         }  
    119.     }  
    120. }  

    测试后发现xml转换为json时也有问题,居然不认识数组,真是悲剧。好吧就由它吧,也可能是我的方法不正确。


    jackson一直很主流,社区和文档支持也很充足,但有人还是嫌它不够快,不够简洁,于是便有了fastjson,看名字就知道它的主要特点就是快,可能在功能和其他支持方面不能和jackson媲美,但天下武功,唯快不破,这就决定了fastjson有了一定的市场。不解释,直接上代码。

    [plain] view plaincopy
     
    1. <!-- for fastjson -->  
    2. <dependency>  
    3.     <groupId>com.alibaba</groupId>  
    4.     <artifactId>fastjson</artifactId>  
    5.     <version>1.1.33</version>  
    6. </dependency>  

    沃,除了自身零依赖,再看它的API使用。
    使用fastjson实现多种转换:

    [java] view plaincopy
     
    1. package cn.yangyong.fodder.util;  
    2.   
    3. import java.util.Date;  
    4. import java.util.List;  
    5. import java.util.Map;  
    6. import java.util.Map.Entry;  
    7. import com.alibaba.fastjson.JSON;  
    8. import com.alibaba.fastjson.JSONObject;  
    9. import com.alibaba.fastjson.TypeReference;  
    10. import com.alibaba.fastjson.serializer.SerializeConfig;  
    11. import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;  
    12.   
    13. /** 
    14.  * fastjson utils 
    15.  *  
    16.  * @author magic_yy 
    17.  * @see https://github.com/alibaba/fastjson 
    18.  * @see http://code.alibabatech.com/wiki/display/FastJSON 
    19.  */  
    20. public class FastJsonUtils {  
    21.       
    22.     private static SerializeConfig mapping = new SerializeConfig();  
    23.       
    24.     static{  
    25.         mapping.put(Date.classnew SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));  
    26.     }  
    27.       
    28.     /** 
    29.      * javaBean、list、map convert to json string 
    30.      */  
    31.     public static String obj2json(Object obj){  
    32. //      return JSON.toJSONString(obj,SerializerFeature.UseSingleQuotes);//使用单引号  
    33. //      return JSON.toJSONString(obj,true);//格式化数据,方便阅读  
    34.         return JSON.toJSONString(obj,mapping);  
    35.     }  
    36.       
    37.     /** 
    38.      * json string convert to javaBean、map 
    39.      */  
    40.     public static <T> T json2obj(String jsonStr,Class<T> clazz){  
    41.         return JSON.parseObject(jsonStr,clazz);  
    42.     }  
    43.       
    44.     /** 
    45.      * json array string convert to list with javaBean 
    46.      */  
    47.     public static <T> List<T> json2list(String jsonArrayStr,Class<T> clazz){  
    48.         return JSON.parseArray(jsonArrayStr, clazz);  
    49.     }  
    50.       
    51.     /** 
    52.      * json string convert to map 
    53.      */  
    54.     public static <T> Map<String,Object> json2map(String jsonStr){  
    55.         return json2obj(jsonStr, Map.class);  
    56.     }  
    57.       
    58.     /** 
    59.      * json string convert to map with javaBean 
    60.      */  
    61.     public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz){  
    62.         Map<String,T> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, T>>() {});  
    63.         for (Entry<String, T> entry : map.entrySet()) {  
    64.             JSONObject obj = (JSONObject) entry.getValue();  
    65.             map.put(entry.getKey(), JSONObject.toJavaObject(obj, clazz));  
    66.         }  
    67.         return map;  
    68.     }  
    69. }  

    API真的很简洁,很方便,这里依旧只用了部分功能,关于注解部分请大家自行研究。测试代码如下:

    [java] view plaincopy
     
    1. package cn.yangyong.fodder.util;  
    2.   
    3. import java.text.SimpleDateFormat;  
    4. import java.util.ArrayList;  
    5. import java.util.Date;  
    6. import java.util.HashMap;  
    7. import java.util.List;  
    8. import java.util.Map;  
    9.   
    10. import org.junit.Assert;  
    11. import org.junit.Test;  
    12.   
    13. public class FastJsonTest {  
    14.       
    15.     @Test  
    16.     public void test_dateFormat(){  
    17.         Date date = new Date();  
    18.         String json = FastJsonUtils.obj2json(date);  
    19.         String expected = """+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)+""";  
    20.         Assert.assertEquals(expected, json);  
    21.     }  
    22.       
    23.     @Test  
    24.     public void test_obj2json(){  
    25.         User user = new User(1"张三");  
    26.         String json = FastJsonUtils.obj2json(user);  
    27.         Assert.assertEquals("{"id":1,"name":"张三"}", json);  
    28.         List<User> list = new ArrayList<>();  
    29.         list.add(new User(1"张三"));  
    30.         list.add(new User(2"李四"));  
    31.         String json2 = FastJsonUtils.obj2json(list);  
    32.         Assert.assertEquals("[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]", json2);  
    33.         Map<String,User> map = new HashMap<>();  
    34.         map.put("user1"new User(1"张三"));  
    35.         map.put("user2"new User(2"李四"));  
    36.         String json3 = FastJsonUtils.obj2json(map);  
    37.         Assert.assertEquals("{"user1":{"id":1,"name":"张三"},"user2":{"id":2,"name":"李四"}}", json3);  
    38.     }  
    39.       
    40.     @Test  
    41.     public void test_json2obj(){  
    42.         String json = "{"id":1,"name":"张三"}";  
    43.         User user = FastJsonUtils.json2obj(json, User.class);  
    44.         Assert.assertTrue(user.getId()==1&&user.getName().equals("张三"));  
    45.     }  
    46.       
    47.     @Test  
    48.     public void test_json2list(){  
    49.         String json = "[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]";  
    50.         List<User> list = FastJsonUtils.json2list(json, User.class);  
    51.         User user1 = list.get(0);  
    52.         User user2 = list.get(1);  
    53.         Assert.assertTrue(user1.getId()==1&&user1.getName().equals("张三"));  
    54.         Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));  
    55.     }  
    56.       
    57.     @Test  
    58.     public void test_json2map() throws Exception{  
    59.         String json = "{"id":1,"name":"张三"}";  
    60.         Map<String,Object> map = FastJsonUtils.json2map(json);  
    61.         Assert.assertEquals("{id=1, name=张三}", map.toString());  
    62.         String json2 = "{"user2":{"id":2,"name":"李四"},"user1":{"id":1,"name":"张三"}}";  
    63.         Map<String,User> map2 = FastJsonUtils.json2map(json2, User.class);  
    64.         User user1 = map2.get("user1");  
    65.         User user2 = map2.get("user2");  
    66.         Assert.assertTrue(user1.getId()==1&&user1.getName().equals("张三"));  
    67.         Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));  
    68.     }  
    69.       
    70.     private static class User{  
    71.         private int id;  
    72.         private String name;   
    73.           
    74.         public User() {  
    75.         }  
    76.         public User(int id, String name) {  
    77.             this.id = id;  
    78.             this.name = name;  
    79.         }  
    80.         @Override  
    81.         public String toString() {  
    82.             return "{"id":"+id+","name":""+name+""}";  
    83.         }  
    84.         public int getId() {  
    85.             return id;  
    86.         }  
    87.         public void setId(int id) {  
    88.             this.id = id;  
    89.         }  
    90.         public String getName() {  
    91.             return name;  
    92.         }  
    93.         public void setName(String name) {  
    94.             this.name = name;  
    95.         }  
    96.     }  
    97.       
    98. }  

    只有json和javaBean直接的相互转换,没有xml的转换,真可惜。好吧,谁叫人家定位不一样呢,要想功能全还是用jackson吧。

    最后给大家介绍下json和xml之间不依赖javaBean直接相互转换的工具staxon,相比很多时候大家都想动态的将json和xml相互转换却不依赖其他javaBean,自己写真的是很麻烦,要人命,用jackson等其他转换工具时结果都不是我想要的

    比如有下面xml和json,他们是等价的:

    [plain] view plaincopy
     
    1. <Response>  
    2.     <CustID>1300000428</CustID>  
    3.     <CompID>1100000324</CompID>  
    4.     <Items>  
    5.         <Item>  
    6.             <Sku_ProductNo>sku_0004</Sku_ProductNo>  
    7.             <Wms_Code>1700386977</Wms_Code>  
    8.             <Sku_Response>T</Sku_Response>  
    9.             <Sku_Reason></Sku_Reason>  
    10.         </Item>  
    11.         <Item>  
    12.             <Sku_ProductNo>0005</Sku_ProductNo>  
    13.             <Wms_Code>1700386978</Wms_Code>  
    14.             <Sku_Response>T</Sku_Response>  
    15.             <Sku_Reason></Sku_Reason>  
    16.         </Item>  
    17.     </Items>  
    18. </Response>  
    [plain] view plaincopy
     
    1. {  
    2.     "Response" : {  
    3.         "CustID" : 1300000428,  
    4.         "CompID" : 1100000324,  
    5.         "Items" : {  
    6.             "Item" : [ {  
    7.                 "Sku_ProductNo" : "sku_0004",  
    8.                 "Wms_Code" : 1700386977,  
    9.                 "Sku_Response" : "T",  
    10.                 "Sku_Reason" : null  
    11.             }, {  
    12.                 "Sku_ProductNo" : "0005",  
    13.                 "Wms_Code" : 1700386978,  
    14.                 "Sku_Response" : "T",  
    15.                 "Sku_Reason" : null  
    16.             } ]  
    17.         }  
    18.     }  
    19. }  

    下面我们使用staxon来实现上面2种互转

    [plain] view plaincopy
     
    1.       <!-- for staxon -->  
    2. lt;dependency>  
    3. <groupId>de.odysseus.staxon</groupId>  
    4. <artifactId>staxon</artifactId>  
    5. <version>1.2</version>  
    6. lt;/dependency>  

    嗯,没有第三方依赖,上转换代码:

    [java] view plaincopy
     
    1. package cn.yangyong.fodder.util;  
    2.   
    3. import java.io.IOException;  
    4. import java.io.StringReader;  
    5. import java.io.StringWriter;  
    6.   
    7. import javax.xml.stream.XMLEventReader;  
    8. import javax.xml.stream.XMLEventWriter;  
    9. import javax.xml.stream.XMLInputFactory;  
    10. import javax.xml.stream.XMLOutputFactory;  
    11.   
    12. import de.odysseus.staxon.json.JsonXMLConfig;  
    13. import de.odysseus.staxon.json.JsonXMLConfigBuilder;  
    14. import de.odysseus.staxon.json.JsonXMLInputFactory;  
    15. import de.odysseus.staxon.json.JsonXMLOutputFactory;  
    16. import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;  
    17.   
    18. /** 
    19.  * json and xml converter 
    20.  * @author magic_yy 
    21.  * @see https://github.com/beckchr/staxon 
    22.  * @see https://github.com/beckchr/staxon/wiki 
    23.  * 
    24.  */  
    25. public class StaxonUtils {  
    26.       
    27.     /** 
    28.      * json string convert to xml string 
    29.      */  
    30.     public static String json2xml(String json){  
    31.         StringReader input = new StringReader(json);  
    32.         StringWriter output = new StringWriter();  
    33.         JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();  
    34.         try {  
    35.             XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);  
    36.             XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);  
    37.             writer = new PrettyXMLEventWriter(writer);  
    38.             writer.add(reader);  
    39.             reader.close();  
    40.             writer.close();  
    41.         } catch( Exception e){  
    42.             e.printStackTrace();  
    43.         } finally {  
    44.             try {  
    45.                 output.close();  
    46.                 input.close();  
    47.             } catch (IOException e) {  
    48.                 e.printStackTrace();  
    49.             }  
    50.         }  
    51.         if(output.toString().length()>=38){//remove <?xml version="1.0" encoding="UTF-8"?>  
    52.             return output.toString().substring(39);  
    53.         }  
    54.         return output.toString();  
    55.     }  
    56.       
    57.     /** 
    58.      * xml string convert to json string 
    59.      */  
    60.     public static String xml2json(String xml){  
    61.         StringReader input = new StringReader(xml);  
    62.         StringWriter output = new StringWriter();  
    63.         JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(true).prettyPrint(true).build();  
    64.         try {  
    65.             XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);  
    66.             XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);  
    67.             writer.add(reader);  
    68.             reader.close();  
    69.             writer.close();  
    70.         } catch( Exception e){  
    71.             e.printStackTrace();  
    72.         } finally {  
    73.             try {  
    74.                 output.close();  
    75.                 input.close();  
    76.             } catch (IOException e) {  
    77.                 e.printStackTrace();  
    78.             }  
    79.         }  
    80.         return output.toString();  
    81.     }  
    82. }  

    当然,这里我也就只用到了它的部分功能,最主要的还是json和xml直接的转换了撒。其他功能自己看咯,不多做介绍了。测试代码如下:

    [java] view plaincopy
     
    1. package cn.yangyong.fodder.util;  
    2.   
    3. import org.junit.Test;  
    4.   
    5. public class StaxonUtilsTest {  
    6.       
    7.     @Test  
    8.     public void test_json2xml(){  
    9.         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}]}}}";  
    10.         String xml = StaxonUtils.json2xml(json);  
    11.         System.out.println(xml);  
    12.     }  
    13.       
    14.     @Test  
    15.     public void test_xml2json(){  
    16.         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>";  
    17.         String json = StaxonUtils.xml2json(xml);  
    18.         System.out.println(json);  
    19.     }  
    20. }  

     

  • 相关阅读:
    [ZZ]C++中,引用和指针的区别
    面试总结之JAVA
    LeetCode 347. Top K Frequent Elements
    LeetCode 342. Power of Four
    腾讯//删除链表中的节点
    腾讯//删除链表中的节点
    腾讯//相交链表
    腾讯//相交链表
    腾讯//环形链表 II
    腾讯//环形链表 II
  • 原文地址:https://www.cnblogs.com/E-star/p/3748218.html
Copyright © 2020-2023  润新知