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:
- <!-- 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>
Using json-lib to implement multiple transformations
These are more common transformations, not fully written, basically enough, the test code is as follows:
- 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);//Ignore cycles and avoid dead cycles
- config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {//Processing Date Date Conversion
- @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();//It can be formatted with toString(1) for easy reading.
- }
- /**
- * 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);//Whether to retain element type identifier, default true
- xmlSerializer.setElementName("e");//Set element label, default e
- xmlSerializer.setArrayName("a");//Set array label, default a
- xmlSerializer.setObjectName("o");//Set the object label, default o
- return xmlSerializer.write(JSONSerializer.toJSON(jsonString));
- }
- }
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.
- 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, "Zhang San");
- String json = JsonLibUtils.pojo2json(user);
- Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", 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,"Zhang San");
- User user2 = new User(2,"Li Si");
- User[] userArray = new User[]{user1,user2};
- String json2 = JsonLibUtils.object2json(userArray);
- Assert.assertEquals("[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]", json2);
- List<User> userList = new ArrayList<>();
- userList.add(user1);
- userList.add(user2);
- String json3 = JsonLibUtils.object2json(userList);
- Assert.assertEquals("[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]", json3);
- //The key of the map here must be String type
- Map<String,Object> map = new HashMap<>();
- map.put("id", 1);
- map.put("name", "Zhang San");
- String json4 = JsonLibUtils.object2json(map);
- Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", 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\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}", json5);
- }
- @Test
- public void xml2json_test(){
- String xml1 = "<User><id>1</id><name>Zhang San</name></User>";
- String json = JsonLibUtils.xml2json(xml1);
- Assert.assertEquals("{\"id\":\"1\",\"name\":\"Zhang San\"}", 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 is the result of processing an array, but it's not the format we want.
- String expected = "{\"CustID\":\"1300000428\",\"Items\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"0005\"}]}";
- Assert.assertEquals(expected, json2);
- //Actually what we want is expected2, so it's not possible to implement xml to JSON with arrays using json-lib
- String expected2 = "{\"CustID\":\"1300000428\",\"Items\":{\"Item\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"0005\"}]}}";
- Assert.assertEquals(expected2, json2);
- }
- @Test
- public void json2arrays_test(){
- String json = "[\"Zhang San\",\"Li Si\"]";
- Object[] array = JsonLibUtils.json2arrays(json);
- Object[] expected = new Object[] { "Zhang San", "Li Si" };
- ArrayAssertions.assertEquals(expected, array);
- //Cannot convert JSON strings to object arrays
- String json2 = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";
- Object[] array2 = JsonLibUtils.json2arrays(json2);
- User user1 = new User(1,"Zhang San");
- User user2 = new User(2,"Li Si");
- Object[] expected2 = new Object[] { user1, user2 };
- ArrayAssertions.assertEquals(expected2, array2);
- }
- @Test
- public void json2list_test(){
- String json = "[\"Zhang San\",\"Li Si\"]";
- List<String> list = JsonLibUtils.json2list(json, String.class);
- Assert.assertTrue(list.size()==2&&list.get(0).equals("Zhang San")&&list.get(1).equals("Li Si"));
- String json2 = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";
- 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\":\"Zhang San\"}";
- User user = (User) JsonLibUtils.json2pojo(json, User.class);
- Assert.assertEquals(json, user.toString());
- }
- @Test
- public void json2map_test(){
- String json = "{\"id\":1,\"name\":\"Zhang San\"}";
- 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("Zhang San"));
- String json2 = "{\"user2\":{\"id\":2,\"name\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}";
- Map map2 = JsonLibUtils.json2map(json2, User.class);
- System.out.println(map2);
- }
- @Test
- public void json2xml_test(){
- String json = "{\"id\":1,\"name\":\"Zhang San\"}";
- 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\">Zhang San</name></o>\r\n", xml);
- System.out.println(xml);
- String json2 = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";
- 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\">Zhang San</name></e><e class=\"object\"><id type=\"number\">2</id><name type=\"string\">Li Si</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;
- }
- }
- }
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:
We're still starting to code, first of all its dependencies:
- 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
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.
- <!-- 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>
Various transformations are implemented using jackson:
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:
- 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();
- }
- }
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.
- 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, "Zhang San"));
- Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", json);
- List<User> list = new ArrayList<>();
- list.add(new User(1, "Zhang San"));
- list.add(new User(2, "Li Si"));
- String json2 = JacksonUtils.obj2json(list);
- Assert.assertEquals("[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]", json2);
- Map<String,User> map = new HashMap<>();
- map.put("user1", new User(1, "Zhang San"));
- map.put("user2", new User(2, "Li Si"));
- String json3 = JacksonUtils.obj2json(map);
- Assert.assertEquals("{\"user2\":{\"id\":2,\"name\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}", json3);
- }
- @Test
- public void test_json2pojo() throws Exception{
- String json = "{\"id\":1,\"name\":\"Zhang San\"}";
- User user = JacksonUtils.json2pojo(json, User.class);
- Assert.assertTrue(user.getId()==1&&user.getName().equals("Zhang San"));
- }
- @Test
- public void test_json2map() throws Exception{
- String json = "{\"id\":1,\"name\":\"Zhang San\"}";
- Map<String,Object> map = JacksonUtils.json2map(json);
- Assert.assertEquals("{id=1, name=Zhang San}", map.toString());
- String json2 = "{\"user2\":{\"id\":2,\"name\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}";
- 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("Zhang San"));
- Assert.assertTrue(user2.getId()==2&&user2.getName().equals("Li Si"));
- }
- @Test
- public void test_json2list() throws Exception{
- String json = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";
- 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("Zhang San"));
- Assert.assertTrue(user2.getId()==2&&user2.getName().equals("Li Si"));
- }
- @Test
- public void test_map2pojo(){
- Map<String,Object> map = new HashMap<String, Object>();
- map.put("id", 1);
- map.put("name", "Zhang San");
- User user = JacksonUtils.map2pojo(map, User.class);
- Assert.assertTrue(user.getId()==1&&user.getName().equals("Zhang San"));
- System.out.println(user);
- }
- @Test
- public void test_json2xml() throws Exception{
- String json = "{\"id\":1,\"name\":\"Zhang San\"}";
- String xml = JacksonUtils.json2xml(json);
- Assert.assertEquals("<ObjectNode xmlns=\"\"><id>1</id><name>Zhang San</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>Zhang San</name></ObjectNode>";
- String json = JacksonUtils.xml2json(xml);
- Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", 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 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
- 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;
- }
- }
- }
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.
Waugh, in addition to its zero dependency, look at its API usage.
- <!-- for fastjson -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.1.33</version>
- </dependency>
Using fastjson to implement multiple transformations:
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:
- 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. to JSONString (obj, Serializer Feature. UseSingleQuotes); // Use single quotation marks
- //return JSON. to JSONString (obj, true); format data for easy reading
- 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;
- }
- }
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.
- 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, "Zhang San");
- String json = FastJsonUtils.obj2json(user);
- Assert.assertEquals("{\"id\":1,\"name\":\"Zhang San\"}", json);
- List<User> list = new ArrayList<>();
- list.add(new User(1, "Zhang San"));
- list.add(new User(2, "Li Si"));
- String json2 = FastJsonUtils.obj2json(list);
- Assert.assertEquals("[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]", json2);
- Map<String,User> map = new HashMap<>();
- map.put("user1", new User(1, "Zhang San"));
- map.put("user2", new User(2, "Li Si"));
- String json3 = FastJsonUtils.obj2json(map);
- Assert.assertEquals("{\"user1\":{\"id\":1,\"name\":\"Zhang San\"},\"user2\":{\"id\":2,\"name\":\"Li Si\"}}", json3);
- }
- @Test
- public void test_json2obj(){
- String json = "{\"id\":1,\"name\":\"Zhang San\"}";
- User user = FastJsonUtils.json2obj(json, User.class);
- Assert.assertTrue(user.getId()==1&&user.getName().equals("Zhang San"));
- }
- @Test
- public void test_json2list(){
- String json = "[{\"id\":1,\"name\":\"Zhang San\"},{\"id\":2,\"name\":\"Li Si\"}]";
- 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("Zhang San"));
- Assert.assertTrue(user2.getId()==2&&user2.getName().equals("Li Si"));
- }
- @Test
- public void test_json2map() throws Exception{
- String json = "{\"id\":1,\"name\":\"Zhang San\"}";
- Map<String,Object> map = FastJsonUtils.json2map(json);
- Assert.assertEquals("{id=1, name=Zhang San}", map.toString());
- String json2 = "{\"user2\":{\"id\":2,\"name\":\"Li Si\"},\"user1\":{\"id\":1,\"name\":\"Zhang San\"}}";
- 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("Zhang San"));
- Assert.assertTrue(user2.getId()==2&&user2.getName().equals("Li Si"));
- }
- 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;
- }
- }
- }
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:
- <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
- } ]
- }
- }
- }
Well, no third-party dependencies, upconversion code:
- <!-- for staxon -->
- lt;dependency>
- <groupId>de.odysseus.staxon</groupId>
- <artifactId>staxon</artifactId>
- <version>1.2</version>
- lt;/dependency>
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:
- 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();
- }
- }
- 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);
- }
- }
Reprint address:
Introduction of Several Tools for json, javaBean and xml Interchange