dazito
dazito

Reputation: 7980

Deserialize multiple json keys to one field with Jackson

I am calling a REST api that returns a json response like:

{
  "data": {
    "code": {
      "code1": {
        "name": "some-name",
        "value": "0.25"
      },
      "code2": {
        "name": "some-name2",
        "value": "0.88"
      },
      "code3": {
        "name": "some-name3",
        "value": "0.00"
      },
      "code4": {
        "name": "some-name4",
        "value": "-0.11"
      },
      "code5": {
        "name": "some-name5",
        "value": "0.99"
      }
    }
  }
}

And I modeled this to the following POJO (for clarity, I omit Data class):

@Data
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Code {
    @JsonAlias({"code1", "code2", "code3", "code4", "code5"})
    private final CustomCode customCode;
}

This works fine if there is only one object below "code". In the example above, with code1 to code5 CustomCode will only have one of the "codeX" objects - where X is 1, 2, 3, 4, or 5.

I know I could use a Map but I would like to avoid using a map if possible. What I look forward to find is something like:

@Data
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Code {
    @JsonAlias({"code1", "code2", "code3", "code4", "code5"})
    private final List<CustomCode> customCodeList;
}

Where customCodeList will hold each code1 to code5 pojos. So my question is: does Jackson offer some annotation/configuration that allows us to accomplish this?

Upvotes: 1

Views: 1414

Answers (1)

rnov
rnov

Reputation: 445

You could make use of @JsonAnySetter like this:

public static class Code {

    private final List<CustomCode> customCodeList = new ArrayList<>();

    private static final Set<String> ALIASES = ImmutableSet.of("code1", "code2", "...");

    @JsonAnySetter
    private void set(String name, CustomCode value) {
        if (ALIASES.contains(name)) {
            customCodeList.add(value);
        }
    }
}

One downside of this approach is that if your Code object may arrive with unknown fields, you might need to change the second parameter of set to Object and parse it more carefully.

Upvotes: 1

Related Questions