Fastjson API ParseProcess
1. Introduction to Fastjson API ParseProcess
ParseProcess is an interface for programming to extend customized deserialization. fastjson supports the following ParseProcess:
- ExtraProcessor is used to process redundant fields
- ExtraTypeProvider is used to provide type information when processing redundant fields
2. Use ExtraProcessor to handle redundant fields
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\":123,\"name\":\"abc\"}", VO.class, processor); Assert.assertEquals(123, vo.getId()); Assert.assertEquals("abc", vo.getAttributes().get("name"));
3. Use ExtraTypeProvider to provide types for redundant fields
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\":123,\"value\":\"123456\"}", VO.class, processor); Assert.assertEquals(123, vo.getId()); Assert.assertEquals(123456, vo.getAttributes().get("value")); // value本应该是字符串类型的,通过getExtraType的处理变成Integer类型了。