【java】 String类型的键值对,提取对象

Map类型的String

  Map map = JacksonUtil.toObject(json, HashMap.class);
     map.get("key");



public class JacksonUtil {

    private static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // 忽略未知字段
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // null 转为空字符串
        mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator,
                                  SerializerProvider serializerProvider) throws IOException {

                jsonGenerator.writeString("");
            }
        });
    }

    public static String toJson(Object obj){
        String rs = null;
        try {
            rs = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public static <T> T toObject(String content, Class<T> clazz) throws IOException {

        return mapper.readValue(content, clazz);
    }

    public static List toList(String content, Class clazz) throws IOException {
        JavaType javaType = getCollectionType(ArrayList.class, clazz);

        return mapper.readValue(content, 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);
    }
}

Json类型的String

JSONObject object = JSON.parseObject(ress); // alibaba Json
object.getJSONObject("regeocode").get("formatted_address").toString();

其中,如果是嵌套的json,用getJSONObject之后再get具体的key

发布了28 篇原创文章 · 获赞 1 · 访问量 2万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览