如何映射包括点在内的JSON键?

发布于 2025-01-19 04:59:54 字数 348 浏览 0 评论 0原文

我有一个JSON,其中一些钥匙包括点。 例如:

{
    "key.1" : 10,
    "key.2" : 20,
    "key.3" : 30
}

我打算使用杰克逊(Jackson)将其映射到MyClass模型对象中:

ObjectMapper mapper = new ObjectMapper();
MyClass obj = mapper.readValue(json, MyClass.class

当然,我无法在其名称中创建具有点的类成员。

那么,有没有办法克服这种情况?

杰克逊是首选,但不是强制性的。

I have a json in which some of its keys include dots.
for example:

{
    "key.1" : 10,
    "key.2" : 20,
    "key.3" : 30
}

I was planning to use Jackson to map it into a MyClass model object using something like:

ObjectMapper mapper = new ObjectMapper();
MyClass obj = mapper.readValue(json, MyClass.class

Of course I cannot create class members with dots in their names.

So, is there a way to overcome this situation?

Jackson is preferred but not mandatory.

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

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

发布评论

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

评论(1

ゞ花落谁相伴 2025-01-26 04:59:54

只需在字段声明的顶部使用注释@jsonproperty,其名称与字段的名称不同:

@JsonProperty("key.1")
private final int key1;
@JsonProperty("key.2")
private final int key2;
@JsonProperty("key.3")
private final int key3;

作为一般说明,杰克逊将json键映射到字段名称​​唯一如果您没有指定其他任何内容(因此会通过反射进行)。
但是,使用杰克逊可以使用其注释来修改字段的名称(不仅)。

附带说明,您还需要注释构造函数参数,以使对象从JSON到JAVA对象进行启用:

@JsonCreator
public MyClass(
    @JsonProperty(value = "key.1", required = true) int key1,
    @JsonProperty(value = "key.2", required = true) int key2,
    @JsonProperty(value = "key.3", required = true) int key3) {
    this.key1 = key1;
    this.key2 = key2;
    this.key3 = key3;
}

...然后您将能够做您想做的事情:

MyClass obj = mapper.readValue(json, MyClass.class);

Just use the annotation @JsonProperty on top of the field declaration, with a name that is different than the field's name:

@JsonProperty("key.1")
private final int key1;
@JsonProperty("key.2")
private final int key2;
@JsonProperty("key.3")
private final int key3;

As a general note, Jackson will map the Json key to the field name only if you don't specify anything else (so it will go by reflection).
However, with Jackson is possible to modify the names of the fields (and not only) using their annotations.

As a side note, you'll also need to annotate the constructor parameters to deserialize the object from Json to Java object:

@JsonCreator
public MyClass(
    @JsonProperty(value = "key.1", required = true) int key1,
    @JsonProperty(value = "key.2", required = true) int key2,
    @JsonProperty(value = "key.3", required = true) int key3) {
    this.key1 = key1;
    this.key2 = key2;
    this.key3 = key3;
}

... then you will be able to do what you wanted:

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