jackson json和对象,集合的几种转换
package com.crm.net.util; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.JavaType; public class JsonUtils<T> { // ObjectMapper mapper2 = new ObjectMapper(); // LoginInfo user = mapper2.readValue(result.toString(), LoginInfo.class); // System.out.println("user:" + user); /** * 转换为 list * * @param josn * @param clz * @return */ public List<T> jsonConverList(String josn, Class clz) { ObjectMapper jacksonMapper = new ObjectMapper(); List<T> me = null; try { jacksonMapper .disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES); // jacksonMapper.enableDefaultTyping(); // jacksonMapper.setVisibility(JsonMethod.FIELD,JsonAutoDetect.Visibility.ANY); // jacksonMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, // false);//格式化 // jacksonMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); // jacksonMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, // false); JavaType javaType = jacksonMapper.getTypeFactory() .constructParametricType(List.class, clz);// clz.selGenType().getClass() me = jacksonMapper.readValue(josn, javaType); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return me; } /** * 转换对象里面有json * * @param josn * @param clz * @return */ public T jsonConverObject(String josn, Class<T> clz) { T t = null; // ObjectMapper jacksonMapper = new ObjectMapper(); InputStreamReader in = new InputStreamReader(new ByteArrayInputStream( josn.getBytes())); BufferedReader streamReader = new BufferedReader(in); StringBuilder buff = new StringBuilder(); String inputStr; try { while ((inputStr = streamReader.readLine()) != null) buff.append(inputStr); ObjectMapper mapper = new ObjectMapper(); t = mapper.readValue(buff.toString(), clz); } catch (IOException e) { e.printStackTrace(); } return t; } }
时间: 2024-10-09 23:44:09