map 對比

linbo.yang發表於2024-04-28
package main;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsonDiff {

  public static String decimalTransform(Object obj){
      String value = obj.toString();
      Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$"); // 匹配整數或小數
      Matcher matcher = pattern.matcher(value);
      if(matcher.matches()){
          value=   new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).toString();
      }
      return value;
  }


  public static List<Map<String,String>> transformMapVlaue(List<Map<Object,Object>> datas) {
      List<Map<String,String>> list =new ArrayList<>();
      for (Map<Object, Object> map : datas) {
          Map<String,String> v_map= new HashMap<>();
          for (Map.Entry<Object, Object> entry : map.entrySet()) {
              String key =(String) entry.getKey();
//              String value =(String) entry.getValue().toString();
              String value=(entry.getValue().toString() != null) ?entry.getValue().toString() : "";
               decimalTransform(value);
              v_map.put(key,decimalTransform(value));
          }
          list.add(v_map);
      }


          return list ;


  }


    public static void main(String[] args) {

        String jsonString = "[{\"name\": \"Alice\", \"age\": 30}, {\"name\": \"Bob\", \"age\": 25}]";
        ObjectMapper objectMapper = new ObjectMapper();


    }





}

package main;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;


public class JsonToMapExample {
    public static void main(String[] args) {
        String json = "[{\"name\": \"Alice\", \"age\": 30, \"sex\": 1}, {\"name\": \"Bob\", \"age\": 25}, {\"name\": \"Bob\", \"age\":1}]";
        Gson gson = new Gson();
        Type listType = new TypeToken<List<Map<Object, Object>>>(){}.getType();
        List<Map<Object, Object>> list = gson.fromJson(json, listType);
        for (Map<Object, Object> item : list) {
            System.out.println(item);
            for (Map.Entry<Object, Object> entry : item.entrySet()) {

           String  entryValue=   JsonDiff.decimalTransform(entry.getValue());
                System.out.println(entryValue);
            }
        }

      List<Map<String,String>> list_new=   JsonDiff.transformMapVlaue(list);
//        System.out.println(list_new.hashCode());
        for (Map<String, String> entry : list_new) {
            System.out.println(entry+">"+entry.hashCode());

        }



//        System.out.println(list_new);


    }
}

相關文章