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=这是书})