1

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?

dazito
  • 7,740
  • 15
  • 75
  • 117
  • No annotation for that is seems. A [custom deserializer](https://stackoverflow.com/questions/19158345/custom-json-deserialization-with-jackson) could do. – LMC Oct 06 '20 at 20:09
  • Try to use [JsonAnySetter](https://fasterxml.github.io/jackson-annotations/javadoc/2.11/com/fasterxml/jackson/annotation/JsonAnySetter.html) annotation. See similar questions: [JSON Jackson deserialization multiple keys into same field](https://stackoverflow.com/questions/57064917/json-jackson-deserialization-multiple-keys-into-same-field), [How can I deserialize a JSON to a Java class which has known mandatory fields, but can have several unknown fields?](https://stackoverflow.com/questions/57081709/how-can-i-deserialize-a-json-to-a-java-class-which-has-known-mandatory-fields-b) – Michał Ziober Oct 06 '20 at 20:18

1 Answers1

1

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.

rnov
  • 435
  • 2
  • 3