Fastjson中ParseProcess简介说明
下文笔者讲述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类型了。
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。