简体   繁体   中英

How do I teach Jackson to source the same field from two disjunctive JSON objects?

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 (eg 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"?

You can use @JsonAlias like this:

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Item {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM