Fastjson中ParseProcess简介说明

书欣 fastjson 发布时间:2022-07-24 23:11:15 阅读数:8210 1
下文笔者讲述fastjson中ParseProcess简介说明,如下所示

Fastjson API ParseProcess简介

ParseProcess是编程扩展定制反序列化的接口
  fastjson支持如下ParseProcess:
     ExtraProcessor:
	     用于处理多余的字段
     ExtraTypeProvider:
	     用于处理多余字段时提供类型信息

使用ExtraProcessor 处理多余字段

public static class VO {
    private int id;
    private Map<String, Object> attributes = new HashMap<String, Object>();
    public int getId() { return id; }
    public void setId(int id) { this.id = id;}
    public Map<String, Object> getAttributes() { return attributes;}
}

ExtraProcessor processor = new ExtraProcessor() {
    public void processExtra(Object object, String key, Object value) {
        VO vo = (VO) object;
        vo.getAttributes().put(key, value);
    }
};


VO vo = JSON.parseObject("{\"id\":8888,\"name\":\"java265\"}", VO.class, processor);
Assert.assertEquals(888, vo.getId());
Assert.assertEquals("java265", vo.getAttributes().get("name"));

使用ExtraTypeProvider 为多余的字段提供类型

public static class VO {
    private int id;
    private Map<String, Object> attributes = new HashMap<String, Object>();
    public int getId() { return id; }
    public void setId(int id) { this.id = id;}
    public Map<String, Object> getAttributes() { return attributes;}
}

class MyExtraProcessor implements ExtraProcessor, ExtraTypeProvider {
    public void processExtra(Object object, String key, Object value) {
        VO vo = (VO) object;
        vo.getAttributes().put(key, value);
    }

    public Type getExtraType(Object object, String key) {
        if ("value".equals(key)) {
            return int.class;
        }
        return null;
    }
};
ExtraProcessor processor = new MyExtraProcessor();

VO vo = JSON.parseObject("{\"id\":888,\"value\":\"265\"}", VO.class, processor);
Assert.assertEquals(888, vo.getId());
Assert.assertEquals("265", vo.getAttributes().get("value")); 
// value本应该是字符串类型的,通过getExtraType的处理变成Integer类型了。
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/fastjson/2022/4045.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者