我如何教杰克逊从两个分离的JSON对象中获取同一字段?
我有一些以多种形式存在的现有数据,但需要读为同一类。
例如,给定课程:
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Item {
private UUID itemId;
}
我可能有一些形式良好且可在开箱即用(例如list< item>
)的JSON:
{
"items": [
{
"itemId": "<uuid>"
}
]
}
但是有些不是:
{
"items": [
{
"someItemId": "<uuid>"
}
]
}
i没有源JSON,它同时包含这两个字段。
我试图使用这个问题,但是我的用例有所不同,因为我本质上会做类似的事情:
try {
Item item = defaultDeserializer.deserialize(...);
} catch (UnrecognizedPropertyException e) {
// try to rebuild object manually by traversing the tree
}
这很难做正确的事,因为我不能让杰克逊再做一次繁重的工作。有其他方法吗?是否有一种基于注释的方法可以允许“从这些JSON字段中的任何一个来源”之类的东西,但并非两者都可以”?
I have the case where I have some existing data which is present in multiple forms, but needs to be read into the same class.
For example, given the class:
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Item {
private UUID itemId;
}
I might have some JSON that is well-formed and is parseable out-of-the-box (e.g. List<Item>
):
{
"items": [
{
"itemId": "<uuid>"
}
]
}
but also some which is not:
{
"items": [
{
"someItemId": "<uuid>"
}
]
}
I do not have source JSON which contains both of these fields at the same time.
I tried to do this using a custom deserialization handler as described in this question, but my use case is a bit different since I will be essentially doing something like:
try {
Item item = defaultDeserializer.deserialize(...);
} catch (UnrecognizedPropertyException e) {
// try to rebuild object manually by traversing the tree
}
which would be rather difficult to get right since I can't let Jackson do the heavy lifting anymore. Are there alternative ways? Is there perhaps an annotation-based approach that would allow something like "source this field from either one of these JSON fields, but not both"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
@jsonalias
这样:You can use
@JsonAlias
like this: