com.fasterxml.jackson.core
jackson-core
2.2.2
jackson的用法 [url]http://tkhhappyboy.blog.163.com/blog/static/11418581520116131144605/[/url]
Deserialize JSON to ArrayList
package com.rh.util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: pandy
* Date: 13-7-6
* Time: 下午5:26
* To change this template use File | Settings | File Templates.
*/
public class JSONUtils {
private static ObjectMapper getObjectMapper(){
ObjectMapper mapper = new ObjectMapper();
return mapper;
}
public static String bean2str(Object obj) {
try {
ObjectMapper mapper = getObjectMapper();
StringWriter writer = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(writer);
mapper.writeValue(gen, obj);
gen.close();
String json = writer.toString();
writer.close();
return json;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Object str2bean(String json, Class> clazz) {
try {
ObjectMapper mapper = getObjectMapper();
Object domain = mapper.readValue(json, clazz);
return domain;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Object str2list(String json, TypeReference valueTypeRef) {
try {
ObjectMapper mapper = getObjectMapper();
Object domain = mapper.readValue(json, valueTypeRef);
return domain;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Object str2list(String json, Class> clazz) {
try {
ObjectMapper mapper = getObjectMapper();
JavaType type = mapper.getTypeFactory().
constructCollectionType(ArrayList.class, clazz) ;
Object domain = mapper.readValue(json, type);
return domain;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//new TypeReference
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net