【问题标题】:How can I serialize the key values pairs of a map as top level keys in the serialised JSON?如何将映射的键值对序列化为序列化 JSON 中的顶级键?
【发布时间】:2021-11-13 05:59:56
【问题描述】:

上课:

public class MyClass {
    private String id;
    private Map<String, Object> properties;
    ...
}

使用 Jackson,我可以告诉 Jackson(通过注释)将 properties 映射中的键值序列化为 MyClass 序列化中的顶级键值吗?

例如,如果properties 包含几个键值:fruit - applecolor - red 我想生成一个如下所示的 JSON:

{
    "if": "...",
    "fruit": "apple",
    "color": "red"
}

代替:

{
    "if": "...",
    "properties": {
        "fruit": "apple",
        "color": "red"
    }
}

【问题讨论】:

标签: java json serialization jackson


【解决方案1】:

注释@JsonUnwrapped 完全符合您的要求。

【讨论】:

  • 显然 Map 对象在@JsonUnwrapped 没有反应(只有 POJO 对象会)...
【解决方案2】:

如何将映射的键值对序列化为顶级键 序列化的 JSON?

解决您的问题的一种可能方法是为您的 MyClass 类创建一个自定义序列化程序,并使用 JsonSerialize 注释对您的类进行注释:

@JsonSerialize(using = MyClassSerializer.class)
public class MyClass {
    private String id;
    private Map<String, Object> properties;
}

在自定义序列化程序中,您可以遍历 properties 映射并构建对象的表示,如下所示:

public class MyClassSerializer extends JsonSerializer<MyClass> {

    @Override
    public void serialize(MyClass t, JsonGenerator jg, SerializerProvider sp) throws IOException {
        jg.writeStartObject();
        jg.writeStringField("id", t.getId());
        for (Map.Entry<String, Object> entry : t.getProperties().entrySet()) {
            jg.writeObjectField(entry.getKey(), entry.getValue());
        }
        jg.writeEndObject();
    }
}

使用您的数据的示例:

public class Main {

    public static void main(String[] args) throws JsonProcessingException {
        MyClass mc = new MyClass();
        Map<String, Object> properties = Map.of(
                "fruit", "apple",
                "color", "red"
        );
        mc.setId("myid");
        mc.setProperties(properties);
        System.out.println(mc);
        ObjectMapper mapper = new ObjectMapper();
        //it will print {"id":"myid","color":"red","fruit":"apple"}
        System.out.println(mapper.writeValueAsString(mc));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    相关资源
    最近更新 更多