fastjson parseProcess 自定义反序列化


fastjson parseProcess 自定义反序列化

 

 

**********************

相关类与接口

 

ParseProcess

public interface ParseProcess {

}

 

ExtraProcess:解析存储多余字段

public interface ExtraProcessor extends ParseProcess {

    void processExtra(Object object, String key, Object value);
}

 

ExtraTypeProcess:解析多余字段的属性

public interface ExtraTypeProvider extends ParseProcess {

    Type getExtraType(Object object, String key);
}

 

 

**********************

示例

 

@Data
class Book{

    private String id;
    private String name;
    private Double price;

    private Map<String,Object> attributes=new HashMap<>();
}

class CustomParseProcess implements ExtraProcessor, ExtraTypeProvider{

    private List<String> keys= Arrays.asList("id","name","price");

    @Override
    public void processExtra(Object object, String key, Object value) {
        Book book=(Book) object;

        if (!keys.contains(key)){
            book.getAttributes().put(key,value);
        }
    }

    @Override
    public Type getExtraType(Object object, String key) {
        if (key.equals("desc")){
            return String.class;
        }

        return Object.class;
    }
}

public class Test6 {

    public static void main(String[] args){
        String jsonString="{" +
                "\"id\": \"2\","
                +"\"name\": \"瓜田李下\","
                +"\"price\": \"6d\","
                +"\"desc\":\"这是书\""+
                "}";

        Book book= JSON.parseObject(jsonString,Book.class,new CustomParseProcess());
        System.out.println(book);
    }
}

 

*****************

控制台输出

 

Book(id=2, name=瓜田李下, price=6.0, attributes={desc=这是书})

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值