如何使用 Jackson 注释序列化此 JSON?

发布于 2024-10-07 11:25:04 字数 754 浏览 6 评论 0原文

我有以下 JSON:

{ 
    fields : {
            "foo" : "foovalue",
            "bar" : "barvalue"
    }
}

我编写了一个 pojo,如下所示:

public class MyPojo {

    @JsonProperty("fields") 
    private List<Field> fields;

    static class Field {
        @JsonProperty("foo") private String foo;
        @JsonProperty("bar") private String bar;

        //Getters and setters for those 2
}

这显然失败了,因为我的 json 字段“fields”是一个哈希图,而不是一个列表。
我的问题是:是否有任何“神奇”注释可以使 Jackson 将映射键识别为 pojo 属性名称,并将映射值分配给 pojo 属性值?

PS:我真的不想让我的 fields 对象作为...

private Map<String, String> fields;

...因为在我的现实世界 json 中,我在地图值中有复杂的对象,而不仅仅是字符串...

谢谢;-)

Philippe

I have the following JSON :

{ 
    fields : {
            "foo" : "foovalue",
            "bar" : "barvalue"
    }
}

I wrote a pojo as follows :

public class MyPojo {

    @JsonProperty("fields") 
    private List<Field> fields;

    static class Field {
        @JsonProperty("foo") private String foo;
        @JsonProperty("bar") private String bar;

        //Getters and setters for those 2
}

This fails obviously, because my json field "fields" is a hashmap, and not a list.
My question is : is there any "magic" annotation that can make Jackson recognize the map keys as pojo property names, and assign the map values to the pojo property values ?

P.S.: I really don't want to have my fields object as a...

private Map<String, String> fields;

...because in my real-world json I have complex objects in the map values, not just strings...

Thanks ;-)

Philippe

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゃ懵逼小萝莉 2024-10-14 11:25:04

好的,对于该 JSON,您只需稍微修改您的示例,例如:

public class MyPojo {
  public Fields fields;
}

public class Fields {
  public String foo;
  public String bar;
}

因为对象的结构需要与 JSON 的结构保持一致。当然,您可以使用 setter 和 getter 来代替公共字段(甚至可以使用构造函数来代替 setter 或字段),这只是最简单的示例。

您的原始类将生成/使用 JSON 更像:

{ 
  "fields" : [
    {
      "foo" : "foovalue",
      "bar" : "barvalue"
    }
  ]
}

因为列表映射到 JSON 数组。

Ok, for that JSON, you would just modify your example slightly, like:

public class MyPojo {
  public Fields fields;
}

public class Fields {
  public String foo;
  public String bar;
}

since structure of objects needs to align with structure of JSON. You could use setters and getters instead of public fields of course (and even constructors instead of setters or fields), this is just the simplest example.

Your original class would produce/consume JSON more like:

{ 
  "fields" : [
    {
      "foo" : "foovalue",
      "bar" : "barvalue"
    }
  ]
}

because Lists map to JSON arrays.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文