ObjectMapper mapper = new ObjectMapper();
// 排除json字符串中实体类没有的字段
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
String json = "[{"name":"a","password":"345"},{"name":"b","password":"123"}]"; //第一种方法 List<User> list = mapper.readValue(json, new TypeReference<List<User>>(){/**/}); //第二种方法 JavaType javaType = mapper.getTypeFactory().constructCollectionType(List.class, User.class); List<User> list2 = mapper.readValue(json, javaType);
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);
public final ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args) throws Exception{ JavaType javaType = getCollectionType(ArrayList.class, YourBean.class); List<YourBean> lst = (List<YourBean>)mapper.readValue(jsonString, javaType); } /** * 获取泛型的Collection Type * @param collectionClass 泛型的Collection * @param elementClasses 元素类 * @return JavaType Java类型 * @since 1.0 */ public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); }
复杂类型转换
ObjectMapper objectMapper = new ObjectMapper(); // 排除json字符串中实体类没有的字段 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); PledgeCertificate pledgeCertificate; Pledge pledge = new Pledge(); try { pledgeCertificate = objectMapper.readValue(requestBody, PledgeCertificate.class); pledge = objectMapper.readValue(requestBody, Pledge.class); Map<String, Object> map = objectMapper.readValue(requestBody, Map.class); String writeValueAsString = objectMapper.writeValueAsString(map.get("obligee")); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Obligee.class); List<Obligee> obligee = objectMapper.readValue(writeValueAsString,javaType); }catch (IOException e) { return “转换错误”; }
数据格式:(实体类没有obligee字段,先排除)
{
“certificate”:"豫(2016)郑州市不动产权第0026369号",
“debtEnd”: "yyyy-mm-dd",
“debtStart”: "yyyy-mm-dd",
“pledgeType”: "2",
“maxDebtAmount”:88,
“registType”:"0201",
“obligee” :[{
"obligeeType":"1","name":张三","certType":"1","certNo":"4114211..."},{
"obligeeType":"1","name":"李四","certType":"1","certNo":"4114211..."}]
}
{
“certificate”:"豫(2016)郑州市不动产权第0026369号",
“debtEnd”: "yyyy-mm-dd",
“debtStart”: "yyyy-mm-dd",
“pledgeType”: "2",
“maxDebtAmount”:88,
“registType”:"0201",
“obligee” :[{
"obligeeType":"1","name":张三","certType":"1","certNo":"4114211..."},{
"obligeeType":"1","name":"李四","certType":"1","certNo":"4114211..."}]
}