json和Map互换

时间:2019-12-03 18:29:35   收藏:0   阅读:78

demo类

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DateInfo {

    
    private String mockDateTime;

    private String serverDateTime;

    private String currentDate;


}

 测试类

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":"1575363764140_2"},"Key1":{"currentDate":"1575363764140_1"},"Key3":{"currentDate":"1575363764140_3"}}
fromJson = {Key2=DateInfo(mockDateTime=null, serverDateTime=null, currentDate=1575363764140_2), Key1=DateInfo(mockDateTime=null, serverDateTime=null, currentDate=1575363764140_1), Key3=DateInfo(mockDateTime=null, serverDateTime=null, currentDate=1575363764140_3)}
fromJson.equals(map) = true
fromJson.get("Key1").equals(map.get("Key1")) = true

 

原文:https://www.cnblogs.com/shoubianxingchen/p/11978036.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!