• json和Map互换


    demo类

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public class DateInfo {
    
        
        private String mockDateTime;
    
        private String serverDateTime;
    
        private String currentDate;
    
    
    }

     测试类

    import com.citi.cv.cisportal.authsite.controller.managestrategy.module.DateInfo;
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    
    import java.lang.reflect.Type;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Test {
    
        public static void main(String[] args) {
            Map<String, DateInfo> map = new HashMap<>();
            map.put("Key1", DateInfo.builder().currentDate(System.currentTimeMillis() + "_1").build());
            map.put("Key2", DateInfo.builder().currentDate(System.currentTimeMillis() + "_2").build());
            map.put("Key3", DateInfo.builder().currentDate(System.currentTimeMillis() + "_3").build());
    
            Type type = new TypeToken<HashMap<String, DateInfo>>() {
            }.getType();
    
            Gson gson = new Gson();
            String json = gson.toJson(map, type);
            System.out.println("gson.toJson(map) = " + json);
    
            Map<String, DateInfo> fromJson = gson.fromJson(json, type);
            System.out.println("fromJson = " + fromJson);
    
            System.out.println("fromJson.equals(map) = " + fromJson.equals(map));
            System.out.println("fromJson.get("Key1").equals(map.get("Key1")) = " + fromJson.get("Key1").equals(map.get("Key1")));
    
        }
    
    }

    输出结果 

    gson.toJson(map) = {"Key2":{"currentDate":"1575444488009_2"},"Key1":{"currentDate":"1575444488009_1"},"Key3":{"currentDate":"1575444488009_3"}}
    fromJson = {Key2=DateInfo(mockDateTime=null, serverDateTime=null, currentDate=1575444488009_2), Key1=DateInfo(mockDateTime=null, serverDateTime=null, currentDate=1575444488009_1), Key3=DateInfo(mockDateTime=null, serverDateTime=null, currentDate=1575444488009_3)}
    fromJson.equals(map) = true
    fromJson.get("Key1").equals(map.get("Key1")) = true
  • 相关阅读:
    舌尖上的中关村
    解决winform窗体闪烁问题
    24段魔尺,可以折出哪些精美图案(续)
    24段魔尺,可以折出哪些精美图案
    关于Python编程的一些问答
    BZOJ 1025: [SCOI2009]游戏
    BZOJ 1025: [SCOI2009]游戏
    BZOJ 1207: [HNOI2004]打鼹鼠
    BZOJ 1207: [HNOI2004]打鼹鼠
    BZOJ 1046: [HAOI2007]上升序列
  • 原文地址:https://www.cnblogs.com/shoubianxingchen/p/11978036.html
Copyright © 2020-2023  润新知