JsonUtil java

package top.starp.util;

//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.bson.Document;

//import javax.swing.text.Document;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.*;

//import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_ENUMS_USING_TO_STRING;

public class JsonUtil {

   public  static   List<Map<String, Object>> toListOfMaps( JSONArray listData){
//        JsonUtil.toListOfMaps()
        List<Map<String, Object>>resList=new ArrayList<>();
        for (int i = 0; i < listData.size(); i++) {
            JSONObject jsonObject = listData.getJSONObject(i);
//            jsonObject.toj
            String jsonString = JsonUtil.toJsonString(jsonObject);
            Map<String, Object> map = JsonUtil.toMap(jsonString);
            resList.add(map);
        }
        return resList;
    }

    public static   JSONObject toJSONObject (Document document){
        JSONObject apiKeyObj = JSONUtil.parseObj(document.toJson());
        return apiKeyObj;
    }
    public static JSONObject  toJSONObject(Map map){
        String s = JsonUtil.mapToJsonStr(map);
        JSONObject jsonObject = JsonUtil.stringToJson(s);
        return jsonObject;
    }

    public static Map<String, String>  toMap(Document document){
        String json = document.toJson();
        Map<String, Object> mapObj = JsonUtil.toMap(json);
        Map<String, String> map = top.starp.util.MapUtil.convertToStringMap(mapObj);
        return map;
    }
    public static String toJsonArray(List<Map<String, Object>> list) {
        return gson.toJson(list);
    }

   public static JSONArray   hashMapListToJsonArray(  List<HashMap<String, Object>> data ){
//        List> data = new ArrayList<>();

        // 假设data中已经有了一些HashMap数据

        JSONArray jsonArray = new JSONArray();
        for (HashMap<String, Object> map : data) {
            JSONObject jsonObject = new JSONObject(map);
            jsonArray.add(jsonObject);
        }
        return jsonArray;

//        System.out.println(jsonArray.toString());
    }


//    public static String hashMapListToJsonArray(List> list) {
//        return gson.toJson(list);
//    }


    public static List<Map<String, Object>> toListOfMaps(String json) {
        Type type = new TypeToken<List<Map<String, Object>>>() {}.getType();
        try{
            return gson.fromJson(json, type);
        }catch (Exception e){
//            e.printStackTrace();

//            System.out.println(e.getCause());
            System.err.println("===============  toListOfMaps err ===========");
            System.err.println(e.getMessage());
            StringUtils.printException(e);

            System.err.println("json");
            String jsonLittle = StringUtils.subString(json, 70);
            System.err.println(jsonLittle);
//            json.

            System.err.println("type  "+type);
//            System.err.println(type);
            System.err.println("===============  toListOfMaps err up ===========");
        }
        return null;
    }

    private static final Gson gson = new Gson();

    public static String toJson(Object object) {
        return gson.toJson(object);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        return gson.fromJson(json, classOfT);
    }

    public static String toJsonString(Map<String, Object> map) {
        return gson.toJson(map);
    }
    public static Map<String, Object>  toMap(Object jsonObject){

        String jsonString = JsonUtil.toJsonString(jsonObject);
        Map<String, Object> map = JsonUtil.toMap(jsonString);
        return map;
    }

    public static Map<String, Object> toMap(String json) {
        Type type = new TypeToken<Map<String, Object>>() {}.getType();
        return gson.fromJson(json, type);
    }



    public  static   JSONObject filePathToJsonObj(String filePath) throws FileNotFoundException {
        String logData = FileUtil.readAll(filePath);
        JSONObject jsonObject = JsonUtil.stringToJson(logData);
        return  jsonObject;
    }

    public static  JSONObject stringToJson(String string){
        return new JSONObject(string);

    }

    public static List<String> findFieldValues(String jsonString, String targetValue) {
        List<String> resultList = new ArrayList<>();
        JSONObject jsonObject = JSONUtil.parseObj(jsonString);
        findFieldValuesRecursive(jsonObject, targetValue, resultList);
        return resultList;
    }

    public  static   JSONObject  getJSONObject(JSONObject jsonObject,String  key){

        try{
     JSONObject jsonObject1 = jsonObject.getJSONObject(key);
    return jsonObject1;

        }catch (Exception e){
            String funcName="getJSONObject";
            System.err.println("============== getJSONObject  err ==========");
            System.err.println("err: "+ e.getMessage());
            System.err.println("time: "+new Date());
//           e.printStackTrace();
            System.err.println("jsonObject");
            System.err.println(jsonObject);
            System.err.println("key  "+key);
//            System.err.println(key);
            System.err.println("============== getJSONObject err 上面 ==========");
//            throw new RuntimeException(e.getMessage());
            throw new FrontMonitorException(e.getMessage());
//           return null;
        }

    }

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static ArrayNode createArrayNode() {
        return objectMapper.createArrayNode();
    }

    public static ObjectNode createObjectNode() {
        return objectMapper.createObjectNode();
    }

    public static String toJsonString(JsonNode jsonNode) throws IOException {
        return objectMapper.writeValueAsString(jsonNode);
    }

    public static JsonNode parseJson(String jsonString) throws IOException {

        JsonNode jsonNode = objectMapper.readTree(jsonString);

        return jsonNode;
    }
    public  static   JSONArray  getJSONArray(JSONObject jsonObject,String  key){
        try{
            JSONArray jsonArray = jsonObject.getJSONArray(key);
            return  jsonArray;
        }catch (Exception e){
            String errMsg="============== getJSONArray  err ==========\n"+
                    "err: "+ e.getMessage()+"\n"
                    +"time: "+new Date()+"\n"
            +  "jsonObject"+"\n"
                    +jsonObject+"\n"
                    +"key  "+key+"\n"
                    +"============== getJSONArray err 上面 =========="+"\n"
                    ;
            System.err.println(errMsg);

            throw new FrontMonitorException(e.getMessage());
//           return null;
        }

    }

    public static List<String> findByKey(String jsonString, String targetKey) {
        List<String> resultList = new ArrayList<>();
        JSONObject jsonObject = JSONUtil.parseObj(jsonString);
        findFieldKeyRecursive(jsonObject, targetKey, resultList);
        return resultList;
    }
    public static void main(String[] args) {
        String jsonString = "{\"field1\":\"value1\",\"field2\":\"xm\",\"field3\":\"value3\",\"field4\":\"xm\"}";
//        List xmList = findFieldValues(jsonString, "xm");
        List<String> xmList = findByKey(jsonString, "xm");
        System.out.println(xmList); // 输出: [field2, field4]
    }

    private static void findFieldValuesRecursive(JSONObject jsonObject, String targetValue, List<String> resultList) {
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            if (value instanceof String && targetValue.equals(value)) {
                resultList.add(key);
            } else if (value instanceof JSONObject) {
                findFieldValuesRecursive((JSONObject) value, targetValue, resultList);
            } else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                for (Object element : array) {
                    if (element instanceof JSONObject) {
                        findFieldValuesRecursive((JSONObject) element, targetValue, resultList);
                    }
                }
            }
        }
    }

    private static void findFieldKeyRecursive(JSONObject jsonObject, String targetValue, List<String> resultList) {
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            if (value instanceof String && targetValue.equals(key)) {
                String strVal=   (String)   value;
                resultList.add(strVal);
            } else if (value instanceof JSONObject) {
                findFieldKeyRecursive((JSONObject) value, targetValue, resultList);
            } else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                for (Object element : array) {
                    if (element instanceof JSONObject) {
                        findFieldKeyRecursive((JSONObject) element, targetValue, resultList);
                    }
                }
            }
        }
    }

    public static String mapToJsonStr(Map map){

        // 创建JSONObject对象
        JSONObject jsonObject = new JSONObject(map);

        // 将JSONObject转换为JSON字符串
        String jsonString = jsonObject.toString();
        System.out.println(jsonString);

        return jsonString;
    }

    public static String toJsonString(Object object) {

        JSONObject jsonObject = new JSONObject(object);

        String jsonString = jsonObject.toString();
        System.out.println(jsonString);

        return jsonString;
    }

    public static void  jsonObjWriteToFile(Object object,String filePath ) throws IOException {
        String s = toJsonString(object);
        FileUtil.writeToFile(filePath,s);
    }

    public static     List<String >  jsonArrayToList(JSONArray jsonArray) {
        List<String > list=new ArrayList<>();
        for (Object o : jsonArray) {
            list.add((String) o);
        }
        return list;
    }

    public static      Map<String, Object>jsonStringToMap(String jsonString){
        Map<String, Object> map = JSONUtil.parseObj(jsonString).toBean(Map.class);
        return map;
    }



}

你可能感兴趣的:(java,java,windows,开发语言)