Use class name as root key for JSON Jackson serialization

前端 未结 11 2798
长情又很酷
长情又很酷 2020-11-27 18:05

Suppose I have a pojo:

import org.codehaus.jackson.map.*;

public class MyPojo {
    int id;
    public int getId()
    { return this.id; }

    public void          


        
11条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 18:25

    there is another way i used and that worked for me. I am working with a third party jar, so i have no control for annotations. So i had to write through bit of hack.

    Override: org.codehaus.jackson.map.ser.BeanSerializerFactory.findBeanProperties(SerializationConfig, BasicBeanDescription)

    Add your property as below

    List props = super.findBeanProperties(config, beanDesc);
    BeanPropertyWriter bpw = null;
    try {
         Class cc = beanDesc.getType().getRawClass();
         Method m = cc.getMethod("getClass", null);
         bpw = new BeanPropertyWriter("$className", null, null, m, null,true, null);
    } catch (SecurityException e) {
      // TODO
    } catch (NoSuchMethodException e) {
      // TODO
    }
    props.add(bpw);
    return props;
    

    This way i get more control and can do other kind of filters too.

提交回复
热议问题