Custom Jackson Deserializer Getting Access to Current Field Class

前端 未结 4 983
遥遥无期
遥遥无期 2021-01-05 07:13

I\'m trying to write a custom deserializer for Jackson and I want to make it generic (generic in the sense of working on any type, not as in \"generics\").

However I

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 07:40

    Roughly speaking, and without exception catching and error checking...

    JsonToken tok = jp.nextValue();
    
    Field field = findField(jp.getCurrentName());
    
    Class fc = field.getType();
    
    if(fc == int.class) {
       field.setInt(this, jp.getIntValue());
    } // handle all the primitive types and String in the same way, then...
    } ... else if(tok == JsonToken.START_ARRAY) {
       if(fc.isArray()) {
          // Load into an array
       } else if(Collection.class.isAssignableFrom(fc)) {
          // Load into a collection
       } else {
          // throw
       }
    } else if(tok == JsonToken.START_OBJECT) {
       // Recursively create that object from the JSON stream
    }
    

    ... and loop until tok is END_OBJECT. To find a of the current class by name:

    Field findField(String name) {
        for(Class c = getClass(); c != null; c = c.getSuperclass()) {
            for(Field field : c.getDeclaredFields()) {
                if(field.getName().equals(name)) {
                    return field;
                }
            }
        }
    }
    

提交回复
热议问题