您的位置:首页 > 编程语言 > Java开发

Json、JavaBean、Xml之间的相互转换工具

2014-12-24 16:43 585 查看
工作中经常要用到Json、JavaBean、Xml之间的相互转换,用到了很多种方式,这里做下总结,以供参考。

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

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

需要的maven依赖:

[plain] view
plaincopy

<!-- for json-lib -->

<dependency>

<groupId>net.sf.json-lib</groupId>

<artifactId>json-lib</artifactId>

<version>2.4</version>

<classifier>jdk15</classifier>

</dependency>

<dependency>

<groupId>xom</groupId>

<artifactId>xom</artifactId>

<version>1.1</version>

</dependency>

<dependency>

<groupId>xalan</groupId>

<artifactId>xalan</artifactId>

<version>2.7.1</version>

</dependency>

使用json-lib实现多种转换

[java] view
plaincopy

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import javax.swing.text.Document;

import net.sf.ezmorph.Morpher;

import net.sf.ezmorph.MorpherRegistry;

import net.sf.ezmorph.bean.BeanMorpher;

import net.sf.ezmorph.object.DateMorpher;

import net.sf.json.JSON;

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

import net.sf.json.JSONSerializer;

import net.sf.json.JsonConfig;

import net.sf.json.processors.JsonValueProcessor;

import net.sf.json.util.CycleDetectionStrategy;

import net.sf.json.util.JSONUtils;

import net.sf.json.xml.XMLSerializer;

/**

* json-lib utils

* @author magic_yy

* @see json-lib.sourceforge.net/

* @see https://github.com/aalmiray/Json-lib
*

*/

public class JsonLibUtils {

public static JsonConfig config = new JsonConfig();

static{

config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);//忽略循环,避免死循环

config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {//处理Date日期转换

@Override

public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date d=(Date) arg1;

return sdf.format(d);

}

@Override

public Object processArrayValue(Object arg0, JsonConfig arg1) {

return null;

}

});

}

/**

* java object convert to json string

*/

public static String pojo2json(Object obj){

return JSONObject.fromObject(obj,config).toString();//可以用toString(1)来实现格式化,便于阅读

}

/**

* array、map、Javabean convert to json string

*/

public static String object2json(Object obj){

return JSONSerializer.toJSON(obj).toString();

}

/**

* xml string convert to json string

*/

public static String xml2json(String xmlString){

XMLSerializer xmlSerializer = new XMLSerializer();

JSON json = xmlSerializer.read(xmlString);

return json.toString();

}

/**

* xml document convert to json string

*/

public static String xml2json(Document xmlDocument){

return xml2json(xmlDocument.toString());

}

/**

* json string convert to javaBean

* @param <T>

*/

@SuppressWarnings("unchecked")

public static <T> T json2pojo(String jsonStr,Class<T> clazz){

JSONObject jsonObj = JSONObject.fromObject(jsonStr);

T obj = (T) JSONObject.toBean(jsonObj, clazz);

return obj;

}

/**

* json string convert to map

*/

public static Map<String,Object> json2map(String jsonStr){

JSONObject jsonObj = JSONObject.fromObject(jsonStr);

Map<String,Object> result = (Map<String, Object>) JSONObject.toBean(jsonObj, Map.class);

return result;

}

/**

* json string convert to map with javaBean

*/

public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz){

JSONObject jsonObj = JSONObject.fromObject(jsonStr);

Map<String,T> map = new HashMap<String, T>();

Map<String,T> result = (Map<String, T>) JSONObject.toBean(jsonObj, Map.class, map);

MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();

Morpher dynaMorpher = new BeanMorpher(clazz,morpherRegistry);

morpherRegistry.registerMorpher(dynaMorpher);

morpherRegistry.registerMorpher(new DateMorpher(new String[]{ "yyyy-MM-dd HH:mm:ss" }));

for (Entry<String,T> entry : result.entrySet()) {

map.put(entry.getKey(), (T)morpherRegistry.morph(clazz, entry.getValue()));

}

return map;

}

/**

* json string convert to array

*/

public static Object[] json2arrays(String jsonString) {

JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(jsonString);

// JSONArray jsonArray = JSONArray.fromObject(jsonString);

JsonConfig jsonConfig = new JsonConfig();

jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);

Object[] objArray = (Object[]) JSONSerializer.toJava(jsonArray,jsonConfig);

return objArray;

}

/**

* json string convert to list

* @param <T>

*/

@SuppressWarnings({ "unchecked", "deprecation" })

public static <T> List<T> json2list(String jsonString, Class<T> pojoClass){

JSONArray jsonArray = JSONArray.fromObject(jsonString);

return JSONArray.toList(jsonArray, pojoClass);

}

/**

* object convert to xml string

*/

public static String obj2xml(Object obj){

XMLSerializer xmlSerializer = new XMLSerializer();

return xmlSerializer.write(JSONSerializer.toJSON(obj));

}

/**

* json string convert to xml string

*/

public static String json2xml(String jsonString){

XMLSerializer xmlSerializer = new XMLSerializer();

xmlSerializer.setTypeHintsEnabled(true);//是否保留元素类型标识,默认true

xmlSerializer.setElementName("e");//设置元素标签,默认e

xmlSerializer.setArrayName("a");//设置数组标签,默认a

xmlSerializer.setObjectName("o");//设置对象标签,默认o

return xmlSerializer.write(JSONSerializer.toJSON(jsonString));

}

}

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

[java] view
plaincopy

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import net.sf.ezmorph.test.ArrayAssertions;

import org.junit.Assert;

import org.junit.Test;

public class JsonLibUtilsTest {

@Test

public void pojo2json_test(){

User user = new User(1, "张三");

String json = JsonLibUtils.pojo2json(user);

Assert.assertEquals("{\"id\":1,\"name\":\"张三\"}", json);

}

@Test

public void object2json_test(){

int[] intArray = new int[]{1,4,5};

String json = JsonLibUtils.object2json(intArray);

Assert.assertEquals("[1,4,5]", json);

User user1 = new User(1,"张三");

User user2 = new User(2,"李四");

User[] userArray = new User[]{user1,user2};

String json2 = JsonLibUtils.object2json(userArray);

Assert.assertEquals("[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]", json2);

List<User> userList = new ArrayList<>();

userList.add(user1);

userList.add(user2);

String json3 = JsonLibUtils.object2json(userList);

Assert.assertEquals("[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]", json3);

//这里的map的key必须为String类型

Map<String,Object> map = new HashMap<>();

map.put("id", 1);

map.put("name", "张三");

String json4 = JsonLibUtils.object2json(map);

Assert.assertEquals("{\"id\":1,\"name\":\"张三\"}", json4);

Map<String,User> map2 = new HashMap<>();

map2.put("user1", user1);

map2.put("user2", user2);

String json5 = JsonLibUtils.object2json(map2);

Assert.assertEquals("{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"张三\"}}", json5);

}

@Test

public void xml2json_test(){

String xml1 = "<User><id>1</id><name>张三</name></User>";

String json = JsonLibUtils.xml2json(xml1);

Assert.assertEquals("{\"id\":\"1\",\"name\":\"张三\"}", json);

String xml2 = "<Response><CustID>1300000428</CustID><Items><Item><Sku_ProductNo>sku_0004</Sku_ProductNo></Item><Item><Sku_ProductNo>0005</Sku_ProductNo></Item></Items></Response>";

String json2 = JsonLibUtils.xml2json(xml2);

//处理数组时expected是处理结果,但不是我们想要的格式

String expected = "{\"CustID\":\"1300000428\",\"Items\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"0005\"}]}";

Assert.assertEquals(expected, json2);

//实际上我们想要的是expected2这种格式,所以用json-lib来实现含有数组的xml to json是不行的

String expected2 = "{\"CustID\":\"1300000428\",\"Items\":{\"Item\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"0005\"}]}}";

Assert.assertEquals(expected2, json2);

}

@Test

public void json2arrays_test(){

String json = "[\"张三\",\"李四\"]";

Object[] array = JsonLibUtils.json2arrays(json);

Object[] expected = new Object[] { "张三", "李四" };

ArrayAssertions.assertEquals(expected, array);

//无法将JSON字符串转换为对象数组

String json2 = "[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]";

Object[] array2 = JsonLibUtils.json2arrays(json2);

User user1 = new User(1,"张三");

User user2 = new User(2,"李四");

Object[] expected2 = new Object[] { user1, user2 };

ArrayAssertions.assertEquals(expected2, array2);

}

@Test

public void json2list_test(){

String json = "[\"张三\",\"李四\"]";

List<String> list = JsonLibUtils.json2list(json, String.class);

Assert.assertTrue(list.size()==2&&list.get(0).equals("张三")&&list.get(1).equals("李四"));

String json2 = "[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]";

List<User> list2 = JsonLibUtils.json2list(json2, User.class);

Assert.assertTrue(list2.size()==2&&list2.get(0).getId()==1&&list2.get(1).getId()==2);

}

@Test

public void json2pojo_test(){

String json = "{\"id\":1,\"name\":\"张三\"}";

User user = (User) JsonLibUtils.json2pojo(json, User.class);

Assert.assertEquals(json, user.toString());

}

@Test

public void json2map_test(){

String json = "{\"id\":1,\"name\":\"张三\"}";

Map map = JsonLibUtils.json2map(json);

int id = Integer.parseInt(map.get("id").toString());

String name = map.get("name").toString();

System.out.println(name);

Assert.assertTrue(id==1&&name.equals("张三"));

String json2 = "{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"张三\"}}";

Map map2 = JsonLibUtils.json2map(json2, User.class);

System.out.println(map2);

}

@Test

public void json2xml_test(){

String json = "{\"id\":1,\"name\":\"张三\"}";

String xml = JsonLibUtils.json2xml(json);

Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<o><id type=\"number\">1</id><name type=\"string\">张三</name></o>\r\n", xml);

System.out.println(xml);

String json2 = "[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]";

String xml2 = JsonLibUtils.json2xml(json2);

System.out.println(xml2);

Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<a><e class=\"object\"><id type=\"number\">1</id><name type=\"string\">张三</name></e><e class=\"object\"><id type=\"number\">2</id><name type=\"string\">李四</name></e></a>\r\n", xml2);

}

public static class User{

private int id;

private String name;

public User() {

}

public User(int id, String name) {

this.id = id;

this.name = name;

}

@Override

public String toString() {

return "{\"id\":"+id+",\"name\":\""+name+"\"}";

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

}

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

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

[plain] view
plaincopy

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

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

[plain] view
plaincopy

<!-- for jackson -->

<dependency>

<groupId>com.fasterxml.jackson.dataformat</groupId>

<artifactId>jackson-dataformat-xml</artifactId>

<version>2.1.3</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.1.3</version>

<type>java-source</type>

<scope>compile</scope>

</dependency>

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

使用jackson实现多种转换:

[java] view
plaincopy

package cn.yangyong.fodder.util;

import java.io.StringWriter;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import com.fasterxml.jackson.core.JsonGenerator;

import com.fasterxml.jackson.core.JsonParser;

import com.fasterxml.jackson.core.type.TypeReference;

import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

/**

* jsonson utils

* @see http://jackson.codehaus.org/
* @see https://github.com/FasterXML/jackson
* @see http://wiki.fasterxml.com/JacksonHome
* @author magic_yy

*

*/

public class JacksonUtils {

private static ObjectMapper objectMapper = new ObjectMapper();

private static XmlMapper xmlMapper = new XmlMapper();

/**

* javaBean,list,array convert to json string

*/

public static String obj2json(Object obj) throws Exception{

return objectMapper.writeValueAsString(obj);

}

/**

* json string convert to javaBean

*/

public static <T> T json2pojo(String jsonStr,Class<T> clazz) throws Exception{

return objectMapper.readValue(jsonStr, clazz);

}

/**

* json string convert to map

*/

public static <T> Map<String,Object> json2map(String jsonStr)throws Exception{

return objectMapper.readValue(jsonStr, Map.class);

}

/**

* json string convert to map with javaBean

*/

public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz)throws Exception{

Map<String,Map<String,Object>> map = objectMapper.readValue(jsonStr, new TypeReference<Map<String,T>>() {

});

Map<String,T> result = new HashMap<String, T>();

for (Entry<String, Map<String,Object>> entry : map.entrySet()) {

result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));

}

return result;

}

/**

* json array string convert to list with javaBean

*/

public static <T> List<T> json2list(String jsonArrayStr,Class<T> clazz)throws Exception{

List<Map<String,Object>> list = objectMapper.readValue(jsonArrayStr, new TypeReference<List<T>>() {

});

List<T> result = new ArrayList<>();

for (Map<String, Object> map : list) {

result.add(map2pojo(map, clazz));

}

return result;

}

/**

* map convert to javaBean

*/

public static <T> T map2pojo(Map map,Class<T> clazz){

return objectMapper.convertValue(map, clazz);

}

/**

* json string convert to xml string

*/

public static String json2xml(String jsonStr)throws Exception{

JsonNode root = objectMapper.readTree(jsonStr);

String xml = xmlMapper.writeValueAsString(root);

return xml;

}

/**

* xml string convert to json string

*/

public static String xml2json(String xml)throws Exception{

StringWriter w = new StringWriter();

JsonParser jp = xmlMapper.getFactory().createParser(xml);

JsonGenerator jg = objectMapper.getFactory().createGenerator(w);

while (jp.nextToken() != null) {

jg.copyCurrentEvent(jp);

}

jp.close();

jg.close();

return w.toString();

}

}

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

[java] view
plaincopy

package cn.yangyong.fodder.util;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.junit.Assert;

import org.junit.Test;

import cn.yangyong.fodder.util.JacksonUtils;

public class JacksonUtilsTest {

@Test

public void test_pojo2json() throws Exception{

String json = JacksonUtils.obj2json(new User(1, "张三"));

Assert.assertEquals("{\"id\":1,\"name\":\"张三\"}", json);

List<User> list = new ArrayList<>();

list.add(new User(1, "张三"));

list.add(new User(2, "李四"));

String json2 = JacksonUtils.obj2json(list);

Assert.assertEquals("[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]", json2);

Map<String,User> map = new HashMap<>();

map.put("user1", new User(1, "张三"));

map.put("user2", new User(2, "李四"));

String json3 = JacksonUtils.obj2json(map);

Assert.assertEquals("{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"张三\"}}", json3);

}

@Test

public void test_json2pojo() throws Exception{

String json = "{\"id\":1,\"name\":\"张三\"}";

User user = JacksonUtils.json2pojo(json, User.class);

Assert.assertTrue(user.getId()==1&&user.getName().equals("张三"));

}

@Test

public void test_json2map() throws Exception{

String json = "{\"id\":1,\"name\":\"张三\"}";

Map<String,Object> map = JacksonUtils.json2map(json);

Assert.assertEquals("{id=1, name=张三}", map.toString());

String json2 = "{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"张三\"}}";

Map<String,User> map2 = JacksonUtils.json2map(json2, User.class);

User user1 = map2.get("user1");

User user2 = map2.get("user2");

Assert.assertTrue(user1.getId()==1&&user1.getName().equals("张三"));

Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));

}

@Test

public void test_json2list() throws Exception{

String json = "[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]";

List<User> list = JacksonUtils.json2list(json,User.class);

User user1 = list.get(0);

User user2 = list.get(1);

Assert.assertTrue(user1.getId()==1&&user1.getName().equals("张三"));

Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));

}

@Test

public void test_map2pojo(){

Map<String,Object> map = new HashMap<String, Object>();

map.put("id", 1);

map.put("name", "张三");

User user = JacksonUtils.map2pojo(map, User.class);

Assert.assertTrue(user.getId()==1&&user.getName().equals("张三"));

System.out.println(user);

}

@Test

public void test_json2xml() throws Exception{

String json = "{\"id\":1,\"name\":\"张三\"}";

String xml = JacksonUtils.json2xml(json);

Assert.assertEquals("<ObjectNode xmlns=\"\"><id>1</id><name>张三</name></ObjectNode>", xml);

String json2 = "{\"Items\":{\"RequestInterfaceSku\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"sku_0005\"}]}}";

String xml2 = JacksonUtils.json2xml(json2);

Assert.assertEquals("<ObjectNode xmlns=\"\"><Items><RequestInterfaceSku><Sku_ProductNo>sku_0004</Sku_ProductNo></RequestInterfaceSku><RequestInterfaceSku><Sku_ProductNo>sku_0005</Sku_ProductNo></RequestInterfaceSku></Items></ObjectNode>", xml2);

}

@Test

public void test_xml2json() throws Exception{

String xml = "<ObjectNode xmlns=\"\"><id>1</id><name>张三</name></ObjectNode>";

String json = JacksonUtils.xml2json(xml);

Assert.assertEquals("{\"id\":1,\"name\":\"张三\"}", json);

String xml2 = "<ObjectNode xmlns=\"\"><Items><RequestInterfaceSku><Sku_ProductNo>sku_0004</Sku_ProductNo></RequestInterfaceSku><RequestInterfaceSku><Sku_ProductNo>sku_0005</Sku_ProductNo></RequestInterfaceSku></Items></ObjectNode>";

String json2 = JacksonUtils.xml2json(xml2);

//expected2是我们想要的格式,但实际结果确实expected1,所以用jackson实现xml直接转换为json在遇到数组时是不可行的

String expected1 = "{\"Items\":{\"RequestInterfaceSku\":{\"Sku_ProductNo\":\"sku_0004\"},\"RequestInterfaceSku\":{\"Sku_ProductNo\":\"sku_0005\"}}}";

String expected2 = "{\"Items\":{\"RequestInterfaceSku\":[{\"Sku_ProductNo\":\"sku_0004\"},{\"Sku_ProductNo\":\"sku_0005\"}]}}";

Assert.assertEquals(expected1, json2);

Assert.assertEquals(expected2, json2);

}

private static class User{

private int id;

private String name;

public User() {

}

public User(int id, String name) {

this.id = id;

this.name = name;

}

@Override

public String toString() {

return "{\"id\":"+id+",\"name\":\""+name+"\"}";

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

}

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

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

[plain] view
plaincopy

<!-- for fastjson -->

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.1.33</version>

</dependency>

沃,除了自身零依赖,再看它的API使用。

使用fastjson实现多种转换:

[java] view
plaincopy

package cn.yangyong.fodder.util;

import java.util.Date;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson.TypeReference;

import com.alibaba.fastjson.serializer.SerializeConfig;

import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

/**

* fastjson utils

*

* @author magic_yy

* @see https://github.com/alibaba/fastjson
* @see http://code.alibabatech.com/wiki/display/FastJSON
*/

public class FastJsonUtils {

private static SerializeConfig mapping = new SerializeConfig();

static{

mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));

}

/**

* javaBean、list、map convert to json string

*/

public static String obj2json(Object obj){

// return JSON.toJSONString(obj,SerializerFeature.UseSingleQuotes);//使用单引号

// return JSON.toJSONString(obj,true);//格式化数据,方便阅读

return JSON.toJSONString(obj,mapping);

}

/**

* json string convert to javaBean、map

*/

public static <T> T json2obj(String jsonStr,Class<T> clazz){

return JSON.parseObject(jsonStr,clazz);

}

/**

* json array string convert to list with javaBean

*/

public static <T> List<T> json2list(String jsonArrayStr,Class<T> clazz){

return JSON.parseArray(jsonArrayStr, clazz);

}

/**

* json string convert to map

*/

public static <T> Map<String,Object> json2map(String jsonStr){

return json2obj(jsonStr, Map.class);

}

/**

* json string convert to map with javaBean

*/

public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz){

Map<String,T> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, T>>() {});

for (Entry<String, T> entry : map.entrySet()) {

JSONObject obj = (JSONObject) entry.getValue();

map.put(entry.getKey(), JSONObject.toJavaObject(obj, clazz));

}

return map;

}

}

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

[java] view
plaincopy

package cn.yangyong.fodder.util;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.junit.Assert;

import org.junit.Test;

public class FastJsonTest {

@Test

public void test_dateFormat(){

Date date = new Date();

String json = FastJsonUtils.obj2json(date);

String expected = "\""+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)+"\"";

Assert.assertEquals(expected, json);

}

@Test

public void test_obj2json(){

User user = new User(1, "张三");

String json = FastJsonUtils.obj2json(user);

Assert.assertEquals("{\"id\":1,\"name\":\"张三\"}", json);

List<User> list = new ArrayList<>();

list.add(new User(1, "张三"));

list.add(new User(2, "李四"));

String json2 = FastJsonUtils.obj2json(list);

Assert.assertEquals("[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]", json2);

Map<String,User> map = new HashMap<>();

map.put("user1", new User(1, "张三"));

map.put("user2", new User(2, "李四"));

String json3 = FastJsonUtils.obj2json(map);

Assert.assertEquals("{\"user1\":{\"id\":1,\"name\":\"张三\"},\"user2\":{\"id\":2,\"name\":\"李四\"}}", json3);

}

@Test

public void test_json2obj(){

String json = "{\"id\":1,\"name\":\"张三\"}";

User user = FastJsonUtils.json2obj(json, User.class);

Assert.assertTrue(user.getId()==1&&user.getName().equals("张三"));

}

@Test

public void test_json2list(){

String json = "[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]";

List<User> list = FastJsonUtils.json2list(json, User.class);

User user1 = list.get(0);

User user2 = list.get(1);

Assert.assertTrue(user1.getId()==1&&user1.getName().equals("张三"));

Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));

}

@Test

public void test_json2map() throws Exception{

String json = "{\"id\":1,\"name\":\"张三\"}";

Map<String,Object> map = FastJsonUtils.json2map(json);

Assert.assertEquals("{id=1, name=张三}", map.toString());

String json2 = "{\"user2\":{\"id\":2,\"name\":\"李四\"},\"user1\":{\"id\":1,\"name\":\"张三\"}}";

Map<String,User> map2 = FastJsonUtils.json2map(json2, User.class);

User user1 = map2.get("user1");

User user2 = map2.get("user2");

Assert.assertTrue(user1.getId()==1&&user1.getName().equals("张三"));

Assert.assertTrue(user2.getId()==2&&user2.getName().equals("李四"));

}

private static class User{

private int id;

private String name;

public User() {

}

public User(int id, String name) {

this.id = id;

this.name = name;

}

@Override

public String toString() {

return "{\"id\":"+id+",\"name\":\""+name+"\"}";

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

}

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

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

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

[plain] view
plaincopy

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

[plain] view
plaincopy

{

"Response" : {

"CustID" : 1300000428,

"CompID" : 1100000324,

"Items" : {

"Item" : [ {

"Sku_ProductNo" : "sku_0004",

"Wms_Code" : 1700386977,

"Sku_Response" : "T",

"Sku_Reason" : null

}, {

"Sku_ProductNo" : "0005",

"Wms_Code" : 1700386978,

"Sku_Response" : "T",

"Sku_Reason" : null

} ]

}

}

}

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

[plain] view
plaincopy

<!-- for staxon -->

lt;dependency>

<groupId>de.odysseus.staxon</groupId>

<artifactId>staxon</artifactId>

<version>1.2</version>

lt;/dependency>

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

[java] view
plaincopy

package cn.yangyong.fodder.util;

import java.io.IOException;

import java.io.StringReader;

import java.io.StringWriter;

import javax.xml.stream.XMLEventReader;

import javax.xml.stream.XMLEventWriter;

import javax.xml.stream.XMLInputFactory;

import javax.xml.stream.XMLOutputFactory;

import de.odysseus.staxon.json.JsonXMLConfig;

import de.odysseus.staxon.json.JsonXMLConfigBuilder;

import de.odysseus.staxon.json.JsonXMLInputFactory;

import de.odysseus.staxon.json.JsonXMLOutputFactory;

import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;

/**

* json and xml converter

* @author magic_yy

* @see https://github.com/beckchr/staxon
* @see https://github.com/beckchr/staxon/wiki
*

*/

public class StaxonUtils {

/**

* json string convert to xml string

*/

public static String json2xml(String json){

StringReader input = new StringReader(json);

StringWriter output = new StringWriter();

JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();

try {

XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);

XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);

writer = new PrettyXMLEventWriter(writer);

writer.add(reader);

reader.close();

writer.close();

} catch( Exception e){

e.printStackTrace();

} finally {

try {

output.close();

input.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(output.toString().length()>=38){//remove <?xml version="1.0" encoding="UTF-8"?>

return output.toString().substring(39);

}

return output.toString();

}

/**

* xml string convert to json string

*/

public static String xml2json(String xml){

StringReader input = new StringReader(xml);

StringWriter output = new StringWriter();

JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(true).prettyPrint(true).build();

try {

XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);

XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);

writer.add(reader);

reader.close();

writer.close();

} catch( Exception e){

e.printStackTrace();

} finally {

try {

output.close();

input.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return output.toString();

}

}

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

[java] view
plaincopy

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);

}

}

哦了,就说到这里吧,这几个都研究不深,当工具来用,仅供参考。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息