Jackson,我感觉是在Java与Json之间相互转换的最快速的框架,当然Google的Gson也很不错,但是参照网上有人的性能测试,看起来还是Jackson比较快一点
Jackson处理一般的JavaBean和Json之间的转换只要使用ObjectMapper 对象的readValue和writeValueAsString两个方法就能实现。但是如果要转换复杂类型Collection如 List<YourBean>,那么就需要先反序列化复杂类型 为泛型的Collection Type。
如果是ArrayList<YourBean>那么使用ObjectMapper 的getTypeFactory().constructParametricType(collectionClass, elementClasses);
如果是HashMap<String,YourBean>那么 ObjectMapper 的getTypeFactory().constructParametricType(HashMap.class,String.class, YourBean.class);
实例:
<pre name="code" class="java">import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Cesi {
public static void main(String[] args) throws Exception {
ObjectMapper obMapper2 = new ObjectMapper();
Map<String, Object> mapText2 = new HashMap<String, Object>();
List dataList2 = new ArrayList();
//pojo类
TextEntity entyti2 = new TextEntity();
entyti2.setNum(122);
entyti2.setRed("艳红色的22");
entyti2.setGreen("淡绿色的22");
dataList2.add(entyti2);
mapText2.put("textEntity", dataList2);
ArrayList<TextEntity> dataListentity = (ArrayList<TextEntity>) mapText2.get("textEntity");
String json2 = obMapper2.writeValueAsString(dataListentity);
System.out.println("dataListentity json2="+json2);
List<TextEntity> text2 = getslist(json2,TextEntity.class);
System.out.println("EntityList2="+text2.get(0).getGreen());
}
public static <T> T getlist(String str,Class<T> cl) throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
T t = mapper.readValue(str, cl);
return t;
}
public static <T> List<T> getslist(String str,Class<T> cl) throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, cl);
List<T> t = mapper.readValue(str, javaType);
return t;
}
}