json字符串转换对象或列表,多了字段不会报错

2024-10-09 10:56:43 浏览数 (3)

json字符串转换对象或列表,多了字段不会报错

代码语言:javascript复制
//DEMO1 转换对象 应用 riskId
public class Item {
    private String id;
    private String rate;

    public Item(String id, String rate) {
        this.id = id;
        this.rate = rate;
    }

    @Override
    public String toString() {
        return "Item{"  
                "id='"   id   '''  
                ", rate='"   rate   '''  
                '}';
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getRate() {
        return rate;
    }

    public void setRate(String rate) {
        this.rate = rate;
    }
}


Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) ->
                LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")))
                .registerTypeAdapter(LocalDate.class, (JsonDeserializer<LocalDate>) (json, type, jsonDeserializationContext) ->
                        LocalDate.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"))).create();


        //测试riskId                
        String sss = "{"id":"40","rate":"1000","riskId":"560000"}";
        Item test2 = JSON.parseObject(sss,Item.class);
        System.out.println("test2="   test2.toString());


        Item carInfo = gson.fromJson(sss, Item.class);
        System.out.println("carInfo="   carInfo.toString());

//测试结果:如果是json字符串多了字段,在映射转换对象的时候,不会报错。 output: test2=Item{id='40', rate='1000'} carInfo=Item{id='40', rate='1000'}

代码语言:javascript复制
// DEMO2 转换列表
 List<Item> configList = new ArrayList<>();
        configList.add(new Item("1","100"));
        configList.add(new Item("2","100"));
        configList.add(new Item("3","100"));
        configList.add(new Item("4","100"));

String json = JSON.toJSONString(configList);
        System.out.println(json);

        List<Item> configList2 = JSON.parseArray(json,Item.class);
        for (Item item : configList2) {
            System.out.println(GsonUtils.toJson(item));
        }

output: {"id":"1","rate":"100"} {"id":"2","rate":"100"} {"id":"3","rate":"100"} {"id":"4","rate":"100"}

0 人点赞