This repository has been archived by the owner on Oct 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
ObjectDeserializer_cn
wenshao edited this page May 4, 2016
·
2 revisions
fastjson支持注册ObjectDeserializer实现自定义反序列化。要自定义序列化,首先需要实现一个ObjectDeserializer,然后注册到ParserConfig中。
package com.alibaba.fastjson.parser.deserializer;
public interface ObjectDeserializer {
<T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName);
int getFastMatchToken();
}
package com.alibaba.fastjson.parser;
public class ParserConfig {
public void putDeserializer(Type type, ObjectDeserializer deserializer);
}
public static enum OrderActionEnum {
FAIL(1), SUCC(0);
private int code;
OrderActionEnum(int code){
this.code = code;
}
}
public static class Msg {
public OrderActionEnum actionEnum;
public String body;
}
public static class OrderActionEnumDeser implements ObjectDeserializer {
@SuppressWarnings("unchecked")
@Override
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
Integer intValue = parser.parseObject(int.class);
if (intValue == 1) {
return (T) OrderActionEnum.FAIL;
} else if (intValue == 0) {
return (T) OrderActionEnum.SUCC;
}
throw new IllegalStateException();
}
@Override
public int getFastMatchToken() {
return JSONToken.LITERAL_INT;
}
}
ParserConfig.getGlobalInstance().putDeserializer(OrderActionEnum.class, new OrderActionEnumDeser());
{
Msg msg = JSON.parseObject("{\"actionEnum\":1,\"body\":\"A\"}", Msg.class);
Assert.assertEquals(msg.body, "A");
Assert.assertEquals(msg.actionEnum, OrderActionEnum.FAIL);
}
{
Msg msg = JSON.parseObject("{\"actionEnum\":0,\"body\":\"B\"}", Msg.class);
Assert.assertEquals(msg.body, "B");
Assert.assertEquals(msg.actionEnum, OrderActionEnum.SUCC);
}
如有需要修改本注脚,请联系阿里巴巴,
© 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