有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何访问Jacskon自定义序列化程序中的另一个对象?

我想使用一个自定义的Jackson序列化程序来编写一个属性值,该属性值是根据模型中的另一个值确定的。问题是这些值位于不同的对象中。这是我的模型的简化版本

public class MyModel {
    private ObjectA objectA;
    private Object objectB
....
}

public class ObjectA {
    private String myValue; //this is the property that will determine the value in ObjectB
    ......
}

public class ObjectB {
    @JsonSerialize(using=MyCustomSerializer.class)
    private String myOtherValue;// this this the value that will be use my custom serializer
    .....
}

//this is my CustomSerialier

public class MyCustomSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) 
        throws IOException, JsonProcessingException {
         String myOtherValue = (String) value;
         //to process 'myOtherValue' I need access to 'myValue' in ObjectA
    ........
}

}

我不想在MyModel上放一个自定义序列化程序,因为模型非常大,有很多嵌套对象,所以在客户序列化程序中写出来比我想做的更多。是否有方法使用自定义序列化程序访问模型中的其他对象,而不必将其设置为顶级对象


共 (0) 个答案