Json字符串是常用的数据格式,下面提供一个Json和JavaBean转换的工具类,它其实也是基于jackson的:
package com.csdn.myboot.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
/**
*
* @Title: JsonUtils.java
* @Package com.lee.utils
* @Description: 自定义响应结构, 转换类
* Copyright: Copyright (c) 2016
* Company:Nathan.Lee.Salvatore
*
* @author leechenxiang
* @date 2016年4月29日 下午11:05:03
* @version V1.0
*/
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param clazz 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
测试:
@ResponseBody
@RequestMapping("/hello")
public String hello(){
UserDomain user7 = new UserDomain();
user7.setUserId(7);
user7.setUserName("Cristiano Ronaldo");
user7.setPassword("abc123");
user7.setPhone("13900000000");
String cr7 = JsonUtils.objectToJson(user7);
String c = "{\"userId\":7,\"userName\":\"Cristiano Ronaldo\",\"password\":\"abc123\",\"phone\":\"13900000000\"}";
UserDomain u = JsonUtils.jsonToPojo(c, UserDomain.class);
System.out.println(u.toString());
String listc = "[ "+c+" ]";
List<UserDomain> list = JsonUtils.jsonToList(listc,UserDomain.class);
System.out.println(list);
return cr7;
}