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);
1 public final ObjectMapper mapper = new ObjectMapper(); 2 3 public static void main(String[] args) throws Exception{ 4 JavaType javaType = getCollectionType(ArrayList.class, YourBean.class); 5 List<YourBean> lst = (List<YourBean>)mapper.readValue(jsonString, javaType); 6 } 7 /** 8 * 获取泛型的Collection Type 9 * @param collectionClass 泛型的Collection 10 * @param elementClasses 元素类 11 * @return JavaType Java类型 12 * @since 1.0 13 */ 14 public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { 15 return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); 16 }
其他相关的:
- JavaType javaType = TypeFactory.defaultInstance()
- constructParametrizedType(Page.class,Page.class, CustomerDTO.class);
- Page<CustomerDTO> list = JsonUtil.om().readValue(res, javaType);
- public class JsonUtil {
- /**
- * 返回mapper,忽略未知参数、使用long解析时间
- *
- * @return
- */
- public static ObjectMapper om() {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
- false);
- mapper.configure(
- DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS,
- true);
- return mapper;
- }
- }