Uh oh!
There was an error while loading. Please reload this page.
This repository was archived by the owner on Jul 29, 2026. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 6.4k
ExtraProcessable
wenshao edited this page Apr 16, 2016
·
2 revisions
在fastjson-1.2.9版本后提供了ExtraProcessable接口,用于定制对象的反序列化功能。接口如下
/** * @since 1.2.9 */publicinterfaceExtraProcessable {
voidprocessExtra(Stringkey, Objectvalue);
}如果对象没有对应public setter和public field,就会调用processExtra方法。这个可以用于一些框架实现MapBean对象的json序列化和反序列化。
例如
importjava.io.IOException;
importjava.lang.reflect.Type;
importjava.util.*;
importorg.junit.Assert;
importjunit.framework.TestCase;
importcom.alibaba.fastjson.JSON;
importcom.alibaba.fastjson.parser.deserializer.ExtraProcessable;
importcom.alibaba.fastjson.serializer.*;
publicclassBug_for_issue_265extendsTestCase {
publicvoidtest_for_issue() throwsException {
Useruser = newUser();
user.setName("wenshao");
Stringtext = JSON.toJSONString(user);
Assert.assertEquals("{\"name\":\"wenshao\"}", text);
}
publicvoidtest_for_issue_decode() throwsException {
Stringtext = "{\"name\":\"wenshao\",\"id\":1001}";
Useruser = JSON.parseObject(text, User.class);
Assert.assertEquals("wenshao", user.getName());
Assert.assertEquals(1001, user.getAttribute("id"));
}
publicstaticclassModelimplementsJSONSerializable, ExtraProcessable {
protectedMap<String, Object> attributes = newHashMap<String, Object>();
publicMap<String, Object> getAttributes() {
returnattributes;
}
publicObjectgetAttribute(Stringname) {
returnattributes.get(name);
}
@Overridepublicvoidwrite(JSONSerializerserializer, ObjectfieldName, TypefieldType,
intfeatures) throwsIOException {
serializer.write(attributes); // 定制序列化
}
@OverridepublicvoidprocessExtra(Stringkey, Objectvalue) {
attributes.put(key, value); // 定制反序列化
}
}
publicstaticclassUserextendsModel {
publicStringgetName() {
return (String) attributes.get("name");
}
publicvoidsetName(Stringname) {
attributes.put("name", name);
}
}
}如有需要修改本注脚,请联系阿里巴巴,
© Alibaba Fastjson Develop Team
注明: 版权所有阿里巴巴,请注明版权所有者
If you need to amend this footnote, please contact Alibaba.
© Alibaba Fastjson Develop Team
Note: Copyright Alibaba, please indicate the copyright owner