一个刚刚写的JacksonUtil,先记下来,留着以后用.
===========================
package com.nemo.util;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nemo.entity.User;
/**
* json字符与对像转换
* @author Nemo
*
*/
public final class JsonUtil {
public static ObjectMapper objectMapper;
/**
* 使用泛型方法,把json字符串转换为相应的JavaBean对象。
* (1)转换为普通JavaBean:readValue(json,Student.class)
* (2)转换为List,如List<Student>,将第二个参数传递为Student
* [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
*
* @param jsonStr 要转化的json字符串
* @param valueType 要转化的类型
* @return
*/
public static <T> T readValue(String jsonStr, Class<T> valueType) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* json数组转List
* @param jsonStr 要转化的json字符串
* @param valueTypeRef 要转化的类型
* @return
*/
public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr, valueTypeRef);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 把JavaBean转换为json字符串
*
* @param object 要转化的对象
* @return 返回转换后的json字符串
*/
public static String toJSon(Object object) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Test
public void test() {
List<User> users = new ArrayList<User>();
User user = new User();
user.setAccount("Nemo");
user.setId(1L);
user.setNickname("Nemo");
user.setPassword("123456");
users.add(user);
users.add(user);
String jsonStr = toJSon(users);
System.out.println("{users:"+jsonStr+"}");
@SuppressWarnings("unchecked")
List<User> us = readValue(jsonStr, List.class);
System.out.println(us);
@SuppressWarnings("unchecked")
List<User> rus = readValue(jsonStr, new TypeReference<List>() {});
System.out.println(rus);
}
}