Conversion among Json, JavaBean and Xml

Keywords: JSON xml Java Junit

Json, JavaBean and Xml are often used to transform each other in work. Many ways are used. Here is a summary for reference.

Now the mainstream conversion tools are json-lib, jackson, fast JSON and so on. I will give you a brief introduction one by one, mainly in the form of code to post how to use these tools simply, and more advanced functions need to be further studied.

First of all, json-lib is a very early conversion tool. There are many people who use it. It is totally inappropriate now. There are many shortcomings. The third party that relies on it is more, inefficient, and the API is more cumbersome. He said that it is purely because many people used it in the old projects. No crap, start coding.

Required maven dependencies:

  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>  

Using json-lib to implement multiple transformations

  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);//Ignore cycles and avoid dead cycles  
  35.         config.registerJsonValueProcessor(Date.classnew JsonValueProcessor() {//Processing Date Date Conversion  
  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();//It can be formatted with toString(1) for easy reading.  
  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);//Whether to retain element type identifier, default true  
  152.         xmlSerializer.setElementName("e");//Set element label, default e  
  153.         xmlSerializer.setArrayName("a");//Set array label, default a  
  154.         xmlSerializer.setObjectName("o");//Set the object label, default o  
  155.         return xmlSerializer.write(JSONSerializer.toJSON(jsonString));    
  156.     }  
  157.       
  158. }  
These are more common transformations, not fully written, basically enough, the test code is as follows:

  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"Zhang San");  
  14.         String json = JsonLibUtils.pojo2json(user);  
  15.         Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", 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,"Zhang San");  
  24.         User user2 = new User(2,"Li Si");  
  25.         User[] userArray = new User[]{user1,user2};  
  26.         String json2 = JsonLibUtils.object2json(userArray);  
  27.         Assert.assertEquals("[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]", 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\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]", json3);  
  33.         //The key of the map here must be String type  
  34.         Map<String,Object> map = new HashMap<>();  
  35.         map.put("id"1);  
  36.         map.put("name""Zhang San");  
  37.         String json4 = JsonLibUtils.object2json(map);  
  38.         Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", 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\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}", json5);  
  44.     }  
  45.       
  46.     @Test  
  47.     public void xml2json_test(){  
  48.         String xml1 = "<User><id>1</id><name>Zhang San</name></User>";  
  49.         String json = JsonLibUtils.xml2json(xml1);  
  50.         Assert.assertEquals("{\"id\":\"1\",\"name\":\"Zhang San\"}", 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 is the result of processing an array, but it's not the format we want.  
  54.         String expected = "{\"CustID\":\"1300000428\",\"Items\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"0005\"}]}";  
  55.         Assert.assertEquals(expected, json2);  
  56.         //Actually what we want is expected2, so it's not possible to implement xml to JSON with arrays using json-lib  
  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 = "[\"Zhang San\",\"Li Si\"]";  
  64.         Object[] array = JsonLibUtils.json2arrays(json);  
  65.         Object[] expected = new Object[] { "Zhang San""Li Si" };  
  66.         ArrayAssertions.assertEquals(expected, array);                                                                                              
  67.         //Cannot convert JSON strings to object arrays  
  68.         String json2 = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";  
  69.         Object[] array2 = JsonLibUtils.json2arrays(json2);  
  70.         User user1 = new User(1,"Zhang San");  
  71.         User user2 = new User(2,"Li Si");  
  72.         Object[] expected2 = new Object[] { user1, user2 };  
  73.         ArrayAssertions.assertEquals(expected2, array2);  
  74.     }  
  75.       
  76.     @Test  
  77.     public void json2list_test(){  
  78.         String json = "[\"Zhang San\",\"Li Si\"]";  
  79.         List<String> list = JsonLibUtils.json2list(json, String.class);  
  80.         Assert.assertTrue(list.size()==2&&list.get(0).equals("Zhang San")&&list.get(1).equals("Li Si"));  
  81.         String json2 = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";  
  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\":\"Zhang San\"}";  
  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\":\"Zhang San\"}";  
  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("Zhang San"));  
  101.         String json2 = "{\"user2\":{\"id\":2,\"name\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}";  
  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\":\"Zhang San\"}";  
  109.         String xml = JsonLibUtils.json2xml(json);  
  110.         Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<o><id type=\"number\">1</id><name type=\"string\">Zhang San</name></o>\r\n", xml);  
  111.         System.out.println(xml);  
  112.         String json2 = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";  
  113.         String xml2 = JsonLibUtils.json2xml(json2);  
  114.         System.out.println(xml2);  
  115.         Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<a><e class=\"object\"><id type=\"number\">1</id><name type=\"string\">Zhang San</name></e><e class=\"object\"><id type=\"number\">2</id><name type=\"string\">Li Si</name></e></a>\r\n", 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 has problems in converting XML to JSON with arrays, and in converting JSON to XML, there will be element identifiers such as < o > < a > < E > etc. In general, we may not need them, and we do not know how to filter these element names yet.


Because of the shortcomings of json-lib, it basically stopped updating and did not support annotation conversion. Later, jackson became popular. It was much more efficient than json-lib. It relied less and the community was more active. It was divided into three parts:

  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  
We're still starting to code, first of all its dependencies:

  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>  
Here I would like to say that there are many jackson-based tools, you can find the corresponding dependencies according to your actual needs. I use data format-xml and data bind here to facilitate the conversion of xml.


Various transformations are implemented using jackson:

  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. }  
Only a part of the function is used. The annotation part is not written because it has never been used. You can study it by yourselves. I won't mention it here. The test code for jackson is as follows:

  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"Zhang San"));  
  16.         Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", json);  
  17.         List<User> list = new ArrayList<>();  
  18.         list.add(new User(1"Zhang San"));  
  19.         list.add(new User(2"Li Si"));  
  20.         String json2 = JacksonUtils.obj2json(list);  
  21.         Assert.assertEquals("[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]", json2);  
  22.         Map<String,User> map = new HashMap<>();  
  23.         map.put("user1"new User(1"Zhang San"));  
  24.         map.put("user2"new User(2"Li Si"));  
  25.         String json3 = JacksonUtils.obj2json(map);  
  26.         Assert.assertEquals("{\"user2\":{\"id\":2,\"name\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}", json3);  
  27.     }  
  28.       
  29.     @Test  
  30.     public void test_json2pojo() throws Exception{  
  31.         String json = "{\"id\":1,\"name\":\"Zhang San\"}";  
  32.         User user = JacksonUtils.json2pojo(json, User.class);  
  33.         Assert.assertTrue(user.getId()==1&&user.getName().equals("Zhang San"));  
  34.     }  
  35.       
  36.     @Test  
  37.     public void test_json2map() throws Exception{  
  38.         String json = "{\"id\":1,\"name\":\"Zhang San\"}";  
  39.         Map<String,Object> map = JacksonUtils.json2map(json);  
  40.         Assert.assertEquals("{id=1, name=Zhang San}", map.toString());  
  41.         String json2 = "{\"user2\":{\"id\":2,\"name\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}";  
  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("Zhang San"));  
  46.         Assert.assertTrue(user2.getId()==2&&user2.getName().equals("Li Si"));  
  47.     }  
  48.       
  49.     @Test  
  50.     public void test_json2list() throws Exception{  
  51.         String json = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";  
  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("Zhang San"));  
  56.         Assert.assertTrue(user2.getId()==2&&user2.getName().equals("Li Si"));  
  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""Zhang San");  
  64.         User user = JacksonUtils.map2pojo(map, User.class);  
  65.         Assert.assertTrue(user.getId()==1&&user.getName().equals("Zhang San"));  
  66.         System.out.println(user);  
  67.     }  
  68.       
  69.     @Test  
  70.     public void test_json2xml() throws Exception{  
  71.         String json = "{\"id\":1,\"name\":\"Zhang San\"}";  
  72.         String xml = JacksonUtils.json2xml(json);  
  73.         Assert.assertEquals("<ObjectNode xmlns=\"\"><id>1</id><name>Zhang San</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>Zhang San</name></ObjectNode>";  
  82.         String json = JacksonUtils.xml2json(xml);  
  83.         Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", 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 is the format we want, but the actual result is expected1, so using jackson to convert xml directly to json is not feasible when encountering arrays  
  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. }  
After testing, it was found that there was a problem when xml was converted to json. It was tragic not to know arrays. Well, it's up to it. Maybe my method is incorrect.


jackson has always been mainstream, community and documentation support is also sufficient, but some people still think it is not fast enough, not concise enough, so there is fastjson, look at the name, you know its main characteristics is fast, and may not be able to function and other support jackson comparable, but the world martial arts, only fast, which determines that fastjson has a certain market. No explanation, go directly to the code.

  1. <!-- for fastjson -->  
  2. <dependency>  
  3.     <groupId>com.alibaba</groupId>  
  4.     <artifactId>fastjson</artifactId>  
  5.     <version>1.1.33</version>  
  6. </dependency>  
Waugh, in addition to its zero dependency, look at its API usage.
Using fastjson to implement multiple transformations:

  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. to JSONString (obj, Serializer Feature. UseSingleQuotes); // Use single quotation marks  
  33. //return JSON. to JSONString (obj, true); format data for easy reading  
  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 is really very concise and convenient, here is still only part of the function, about the annotation part, please study by yourself. The test code is as follows:

  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"Zhang San");  
  26.         String json = FastJsonUtils.obj2json(user);  
  27.         Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", json);  
  28.         List<User> list = new ArrayList<>();  
  29.         list.add(new User(1"Zhang San"));  
  30.         list.add(new User(2"Li Si"));  
  31.         String json2 = FastJsonUtils.obj2json(list);  
  32.         Assert.assertEquals("[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]", json2);  
  33.         Map<String,User> map = new HashMap<>();  
  34.         map.put("user1"new User(1"Zhang San"));  
  35.         map.put("user2"new User(2"Li Si"));  
  36.         String json3 = FastJsonUtils.obj2json(map);  
  37.         Assert.assertEquals("{\"user1\":{\"id\":1,\"name\":\"Zhang San\"},\"user2\":{\"id\":2,\"name\":\"Li Si\"}}", json3);  
  38.     }  
  39.       
  40.     @Test  
  41.     public void test_json2obj(){  
  42.         String json = "{\"id\":1,\"name\":\"Zhang San\"}";  
  43.         User user = FastJsonUtils.json2obj(json, User.class);  
  44.         Assert.assertTrue(user.getId()==1&&user.getName().equals("Zhang San"));  
  45.     }  
  46.       
  47.     @Test  
  48.     public void test_json2list(){  
  49.         String json = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";  
  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("Zhang San"));  
  54.         Assert.assertTrue(user2.getId()==2&&user2.getName().equals("Li Si"));  
  55.     }  
  56.       
  57.     @Test  
  58.     public void test_json2map() throws Exception{  
  59.         String json = "{\"id\":1,\"name\":\"Zhang San\"}";  
  60.         Map<String,Object> map = FastJsonUtils.json2map(json);  
  61.         Assert.assertEquals("{id=1, name=Zhang San}", map.toString());  
  62.         String json2 = "{\"user2\":{\"id\":2,\"name\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}";  
  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("Zhang San"));  
  67.         Assert.assertTrue(user2.getId()==2&&user2.getName().equals("Li Si"));  
  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. }  
It's a pity that only json and javaBean are directly converted to each other without xml transformation. Okay, who told people to locate differently? If you want to have all the functions, you should use jackson.


Finally, I will introduce staxon, a tool that does not depend on javaBean to convert directly between json and xml. Comparing with staxon, many times people want to dynamically convert json and XML to each other without depending on other javaBeans, it's very troublesome to write their own reality. It kills lives. When using other conversion tools such as jackson, the result is not what I want.

For example, there are the following xml and json, which are equivalent:

  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>  


  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. }  


Now let's use staxon to implement the above two kinds of interoperability

  1.       <!-- for staxon -->  
  2. lt;dependency>  
  3. <groupId>de.odysseus.staxon</groupId>  
  4. <artifactId>staxon</artifactId>  
  5. <version>1.2</version>  
  6. lt;/dependency>  
Well, no third-party dependencies, upconversion code:

  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. }  
Of course, I only use some of its functions here, the most important thing is the direct conversion of json and xml. Other functions look at themselves, do not do more introductions. The test code is as follows:

  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. }  

Reprint address:

Introduction of Several Tools for json, javaBean and xml Interchange

http://blog.csdn.net/sdyy321/article/details/7024236/

Posted by komquat on Mon, 08 Apr 2019 19:21:32 -0700