简体   繁体   English

自定义串行器和 Jackson 架构

[英]Custom Serializer and Jackson Schema

I have the following two classes:我有以下两个课程:

public class MyChild
{
    @JsonProperty
    public int x;
}
public class MyTest
{
    public void MyChild() {}

    @JsonSerialize(using = MapValueSerializer.class)
    private Map<String, MyChild> childs = new LinkedHashMap<>();
}

where I want childs to serialize as an array of MyChild and not as a map (values only).我希望孩子序列化为MyChild数组,而不是 map (仅限值)。 Thus, I use the following custom serializer:因此,我使用以下自定义序列化程序:

public class MapValueSerializer extends StdSerializer<Map<String, ?>>
{

    protected MapValueSerializer()
    {
        this(null);
    }

    protected MapValueSerializer(Class<Map<String, ?>> t)
    {
        super(t);
    }

    @Override
    public void serialize(Map<String, ?> value, JsonGenerator gen, SerializerProvider provider) throws IOException
    {
        provider.defaultSerializeValue(value.values(), gen);
    }
}

When I now use the JsonSchemaGenerator to generate a schema from MyTest , I get the following:当我现在使用JsonSchemaGeneratorMyTest生成模式时,我得到以下信息:

{
  "type" : "object",
  "id" : "urn:jsonschema:com:myclasses:MyTest",
  "properties" : {
    "childs" : {
      "type" : "any"
    }
  }
}

But childs shouldn't be of type "any" but of type "object".但是孩子不应该是“任何”类型,而是“对象”类型。 If I remove the serializer, the type is "object".如果我删除序列化程序,则类型为“对象”。 Do I have to add something to make the schema generator aware of that type?我是否必须添加一些内容以使模式生成器知道该类型?

It works after I overwrite acceptJsonFormatVisitor() in my MapValueSerializer class with:它在我的MapValueSerializer class 中覆盖acceptJsonFormatVisitor()后工作:

@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException
{
    JavaType valueType = ((MapType) typeHint).getContentType();
    visitor.getProvider().findValueSerializer(valueType).acceptJsonFormatVisitor(visitor, valueType);
}

Then child is of type "object" and also the subelement "x" is generated in the schema.然后 child 是“object”类型,并且在模式中生成子元素“x”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM