赞
踩
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class JacksonUtil { public static ObjectMapper objectMapper; /** * Json字符串中取出指定节点值 * * @param jsonStr json * @param key key * @return */ public static String getValueByKey(String jsonStr, String key) { if (objectMapper == null) { objectMapper = new ObjectMapper(); } try { JsonNode jsonNode = objectMapper.readTree(jsonStr).get(key); if (jsonNode == null) { return null; } if (jsonNode.isTextual()) { return jsonNode.asText(); } else { return jsonNode.toString(); } } catch (IOException e) { e.printStackTrace(); } return null; } /** * @param jsonStr json * @param valueType class * @return T */ public static <T> T readValue(String jsonStr, Class<T> valueType) { if (objectMapper == null) { objectMapper = new ObjectMapper(); } try { return objectMapper.readValue(jsonStr, valueType); } catch (Exception e) { e.printStackTrace(); } return null; } /** * json数组转List * * @param jsonStr * @param valueTypeRef * @return */ public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) { if (objectMapper == null) { objectMapper = new ObjectMapper(); } try { return objectMapper.readValue(jsonStr, valueTypeRef); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 把JavaBean转换为json字符串 * * @param object * @return */ public static String toJSon(Object object) { if (objectMapper == null) { objectMapper = new ObjectMapper(); } try { return objectMapper.writeValueAsString(object); } catch (Exception e) { e.printStackTrace(); } return null; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。