如何映射包括点在内的JSON键?
我有一个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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在字段声明的顶部使用注释
@jsonproperty
,其名称与字段的名称不同:作为一般说明,杰克逊将json键映射到字段名称唯一如果您没有指定其他任何内容(因此会通过反射进行)。
但是,使用杰克逊可以使用其注释来修改字段的名称(不仅)。
附带说明,您还需要注释构造函数参数,以使对象从JSON到JAVA对象进行启用:
...然后您将能够做您想做的事情:
Just use the annotation
@JsonProperty
on top of the field declaration, with a name that is different than the field's name: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:
... then you will be able to do what you wanted: