Deserialize a varying number of objects into a list in Java using Jackson





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















My Spring Boot app makes a call to a REST API and receives a JSON with a varying number of entities. E.g.



{
"content": {
"guest_1": {
"name": {
"firstName": "a",
"lastName": "b"
},
"vip": false
},
"guest_2": {
"name": {
"firstName": "c",
"lastName": "d"
},
"vip": false
},
...more guests omitted...
}
}


There can be 1 to many guests and I don't know their number upfront. As you can see, they aren't in an array, they are objects instead.



I'd like to avoid deserializing into a class like



public class Content {

@JsonProperty("guest_1")
private Guest guest1;

@JsonProperty("guest_2")
private Guest guest2;

// More Guests here each having their own field
}


What I'd like to use is



public class Content {

private List<Guest> guests;
}


The @JsonAnySetter annotation I read about at https://www.baeldung.com/jackson-annotations looks promising but I couldn't get it to work.



3.2. Convert to an object at https://www.baeldung.com/jackson-json-node-tree-model looks also good but it didn't work out either.



I'm not sure if I can make Jackson do this in a declarative way or I should write a custom JsonDeserializer. Could you please help me?










share|improve this question































    2















    My Spring Boot app makes a call to a REST API and receives a JSON with a varying number of entities. E.g.



    {
    "content": {
    "guest_1": {
    "name": {
    "firstName": "a",
    "lastName": "b"
    },
    "vip": false
    },
    "guest_2": {
    "name": {
    "firstName": "c",
    "lastName": "d"
    },
    "vip": false
    },
    ...more guests omitted...
    }
    }


    There can be 1 to many guests and I don't know their number upfront. As you can see, they aren't in an array, they are objects instead.



    I'd like to avoid deserializing into a class like



    public class Content {

    @JsonProperty("guest_1")
    private Guest guest1;

    @JsonProperty("guest_2")
    private Guest guest2;

    // More Guests here each having their own field
    }


    What I'd like to use is



    public class Content {

    private List<Guest> guests;
    }


    The @JsonAnySetter annotation I read about at https://www.baeldung.com/jackson-annotations looks promising but I couldn't get it to work.



    3.2. Convert to an object at https://www.baeldung.com/jackson-json-node-tree-model looks also good but it didn't work out either.



    I'm not sure if I can make Jackson do this in a declarative way or I should write a custom JsonDeserializer. Could you please help me?










    share|improve this question



























      2












      2








      2








      My Spring Boot app makes a call to a REST API and receives a JSON with a varying number of entities. E.g.



      {
      "content": {
      "guest_1": {
      "name": {
      "firstName": "a",
      "lastName": "b"
      },
      "vip": false
      },
      "guest_2": {
      "name": {
      "firstName": "c",
      "lastName": "d"
      },
      "vip": false
      },
      ...more guests omitted...
      }
      }


      There can be 1 to many guests and I don't know their number upfront. As you can see, they aren't in an array, they are objects instead.



      I'd like to avoid deserializing into a class like



      public class Content {

      @JsonProperty("guest_1")
      private Guest guest1;

      @JsonProperty("guest_2")
      private Guest guest2;

      // More Guests here each having their own field
      }


      What I'd like to use is



      public class Content {

      private List<Guest> guests;
      }


      The @JsonAnySetter annotation I read about at https://www.baeldung.com/jackson-annotations looks promising but I couldn't get it to work.



      3.2. Convert to an object at https://www.baeldung.com/jackson-json-node-tree-model looks also good but it didn't work out either.



      I'm not sure if I can make Jackson do this in a declarative way or I should write a custom JsonDeserializer. Could you please help me?










      share|improve this question
















      My Spring Boot app makes a call to a REST API and receives a JSON with a varying number of entities. E.g.



      {
      "content": {
      "guest_1": {
      "name": {
      "firstName": "a",
      "lastName": "b"
      },
      "vip": false
      },
      "guest_2": {
      "name": {
      "firstName": "c",
      "lastName": "d"
      },
      "vip": false
      },
      ...more guests omitted...
      }
      }


      There can be 1 to many guests and I don't know their number upfront. As you can see, they aren't in an array, they are objects instead.



      I'd like to avoid deserializing into a class like



      public class Content {

      @JsonProperty("guest_1")
      private Guest guest1;

      @JsonProperty("guest_2")
      private Guest guest2;

      // More Guests here each having their own field
      }


      What I'd like to use is



      public class Content {

      private List<Guest> guests;
      }


      The @JsonAnySetter annotation I read about at https://www.baeldung.com/jackson-annotations looks promising but I couldn't get it to work.



      3.2. Convert to an object at https://www.baeldung.com/jackson-json-node-tree-model looks also good but it didn't work out either.



      I'm not sure if I can make Jackson do this in a declarative way or I should write a custom JsonDeserializer. Could you please help me?







      java jackson deserialization json-deserialization






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 26 '18 at 16:03







      Andras Szoke

















      asked Nov 26 '18 at 14:34









      Andras SzokeAndras Szoke

      375




      375
























          1 Answer
          1






          active

          oldest

          votes


















          1














          @JsonAnySetter will work as it allows to specify a POJO type as second parameter. You could recreate the example JSON as, omitting setXXX() and getXXX() methods on POJOs for clarity:



          private static class Content {
          private Guests content;
          }

          private static class Guests {
          private List<Guest> guests = new ArrayList<>();

          @JsonAnySetter
          private void addGuest(String name, Guest value) {
          guests.add(value);
          }
          }

          private static class Guest {
          private Name name;
          private boolean vip;
          }

          private static class Name {
          private String firstName;
          private String lastName;
          }


          With your JSON example will produce:



          Content root = new ObjectMapper().readValue(json, Content.class);
          root.getContent().getGuests().stream()
          .map(Guest::getName)
          .map(Name::getFirstName)
          .forEach(System.out::println); // a, c





          share|improve this answer


























          • Wow, this works like a charm! Looks like I was close to the solution but missing something. Instead of a List, I ended up putting the values into a Map where the name parameter is the key. Thanks for your quick response!

            – Andras Szoke
            Nov 26 '18 at 16:05












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53483360%2fdeserialize-a-varying-number-of-objects-into-a-list-in-java-using-jackson%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          @JsonAnySetter will work as it allows to specify a POJO type as second parameter. You could recreate the example JSON as, omitting setXXX() and getXXX() methods on POJOs for clarity:



          private static class Content {
          private Guests content;
          }

          private static class Guests {
          private List<Guest> guests = new ArrayList<>();

          @JsonAnySetter
          private void addGuest(String name, Guest value) {
          guests.add(value);
          }
          }

          private static class Guest {
          private Name name;
          private boolean vip;
          }

          private static class Name {
          private String firstName;
          private String lastName;
          }


          With your JSON example will produce:



          Content root = new ObjectMapper().readValue(json, Content.class);
          root.getContent().getGuests().stream()
          .map(Guest::getName)
          .map(Name::getFirstName)
          .forEach(System.out::println); // a, c





          share|improve this answer


























          • Wow, this works like a charm! Looks like I was close to the solution but missing something. Instead of a List, I ended up putting the values into a Map where the name parameter is the key. Thanks for your quick response!

            – Andras Szoke
            Nov 26 '18 at 16:05
















          1














          @JsonAnySetter will work as it allows to specify a POJO type as second parameter. You could recreate the example JSON as, omitting setXXX() and getXXX() methods on POJOs for clarity:



          private static class Content {
          private Guests content;
          }

          private static class Guests {
          private List<Guest> guests = new ArrayList<>();

          @JsonAnySetter
          private void addGuest(String name, Guest value) {
          guests.add(value);
          }
          }

          private static class Guest {
          private Name name;
          private boolean vip;
          }

          private static class Name {
          private String firstName;
          private String lastName;
          }


          With your JSON example will produce:



          Content root = new ObjectMapper().readValue(json, Content.class);
          root.getContent().getGuests().stream()
          .map(Guest::getName)
          .map(Name::getFirstName)
          .forEach(System.out::println); // a, c





          share|improve this answer


























          • Wow, this works like a charm! Looks like I was close to the solution but missing something. Instead of a List, I ended up putting the values into a Map where the name parameter is the key. Thanks for your quick response!

            – Andras Szoke
            Nov 26 '18 at 16:05














          1












          1








          1







          @JsonAnySetter will work as it allows to specify a POJO type as second parameter. You could recreate the example JSON as, omitting setXXX() and getXXX() methods on POJOs for clarity:



          private static class Content {
          private Guests content;
          }

          private static class Guests {
          private List<Guest> guests = new ArrayList<>();

          @JsonAnySetter
          private void addGuest(String name, Guest value) {
          guests.add(value);
          }
          }

          private static class Guest {
          private Name name;
          private boolean vip;
          }

          private static class Name {
          private String firstName;
          private String lastName;
          }


          With your JSON example will produce:



          Content root = new ObjectMapper().readValue(json, Content.class);
          root.getContent().getGuests().stream()
          .map(Guest::getName)
          .map(Name::getFirstName)
          .forEach(System.out::println); // a, c





          share|improve this answer















          @JsonAnySetter will work as it allows to specify a POJO type as second parameter. You could recreate the example JSON as, omitting setXXX() and getXXX() methods on POJOs for clarity:



          private static class Content {
          private Guests content;
          }

          private static class Guests {
          private List<Guest> guests = new ArrayList<>();

          @JsonAnySetter
          private void addGuest(String name, Guest value) {
          guests.add(value);
          }
          }

          private static class Guest {
          private Name name;
          private boolean vip;
          }

          private static class Name {
          private String firstName;
          private String lastName;
          }


          With your JSON example will produce:



          Content root = new ObjectMapper().readValue(json, Content.class);
          root.getContent().getGuests().stream()
          .map(Guest::getName)
          .map(Name::getFirstName)
          .forEach(System.out::println); // a, c






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 26 '18 at 15:03

























          answered Nov 26 '18 at 14:58









          Karol DowbeckiKarol Dowbecki

          26.4k93759




          26.4k93759













          • Wow, this works like a charm! Looks like I was close to the solution but missing something. Instead of a List, I ended up putting the values into a Map where the name parameter is the key. Thanks for your quick response!

            – Andras Szoke
            Nov 26 '18 at 16:05



















          • Wow, this works like a charm! Looks like I was close to the solution but missing something. Instead of a List, I ended up putting the values into a Map where the name parameter is the key. Thanks for your quick response!

            – Andras Szoke
            Nov 26 '18 at 16:05

















          Wow, this works like a charm! Looks like I was close to the solution but missing something. Instead of a List, I ended up putting the values into a Map where the name parameter is the key. Thanks for your quick response!

          – Andras Szoke
          Nov 26 '18 at 16:05





          Wow, this works like a charm! Looks like I was close to the solution but missing something. Instead of a List, I ended up putting the values into a Map where the name parameter is the key. Thanks for your quick response!

          – Andras Szoke
          Nov 26 '18 at 16:05




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53483360%2fdeserialize-a-varying-number-of-objects-into-a-list-in-java-using-jackson%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Wiesbaden

          Marschland

          Dieringhausen