我如何教杰克逊从两个分离的JSON对象中获取同一字段?

发布于 2025-02-13 09:48:28 字数 1207 浏览 0 评论 0原文

我有一些以多种形式存在的现有数据,但需要读为同一类。

例如,给定课程:

@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 技术交流群。

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

发布评论

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

评论(1

冷了相思 2025-02-20 09:48:28

您可以使用@jsonalias这样:

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Item {

  @JsonAlias("someItemId")
  private UUID itemId;
}

You can use @JsonAlias like this:

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Item {

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