管道基础大数据平台系统开发-【后端】-Server
1
sws
2022-11-26 ab849f796bdc17236a95ea5fe5c166fb8f24a75c
src/main/java/com/lf/server/helper/JsonHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,79 @@
package com.lf.server.helper;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
/**
 * Json帮助类
 * @author WWW
 */
public class JsonHelper {
    /**
     * json串,转为LinkedHashMap
     * @param json
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static LinkedHashMap<String, Object> json2Map(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        return mapper.readValue(json, LinkedHashMap.class);
    }
    /**
     * å¯¹è±¡è½¬json
     * @param obj
     * @return
     * @throws IOException
     */
    public static String map2Json(Object obj) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        return mapper.writeValueAsString(obj);
    }
    /**
     * json串,转为List<LinkedHashMap<String, Object>>
     * @param json
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static List<LinkedHashMap<String, Object>> json2ListMap(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        return mapper.readValue(json, List.class);
    }
    /**
     * å°†json字符串转为对象
     * @param json
     * @param valueType
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T json2Object(String json, Class<T> valueType) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        return mapper.readValue(json, valueType);
    }
    /**
     * fastjson è½¬å¯¹è±¡
     *
     * @param obj
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T obj2Vo(Object obj, Class<T> valueType) {
        return JSONObject.parseObject(JSONObject.toJSONString(obj), valueType);
    }
}