What's the Jackson deserialization equivalent of @JsonUnwrapped?












35















Say I have the following class:



public class Parent {
public int age;
@JsonUnwrapped
public Name name;
}


Producing JSON:



{
"age" : 18,
"first" : "Joey",
"last" : "Sixpack"
}


How do I deserialize this back into the Parent class? I could use @JsonCreator



@JsonCreator
public Parent(Map<String,String> jsonMap) {
age = jsonMap.get("age");
name = new Name(jsonMap.get("first"), jsonMap.get("last"));
}


But this also effectively adds @JsonIgnoreProperties(ignoreUnknown=true) to the Parent class, as all properties map to here. So if you wanted unknown JSON fields to throw an exception, you'd have to do that yourself. In addition, if the map values could be something other than Strings, you'd have to do some manual type checking and conversion. Is there a way for Jackson to handle this case automatically?



Edit:
I might be crazy, but this actually appears to work despite never being explicitly mentioned in the documentation: http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html

I was pretty sure it didn't work for me previously. Still, the proposed @JsonCreator approach might be preferred when custom logic is required to deserialize unwrapped polymorphic types.










share|improve this question




















  • 4





    Are you certain @JsonUnwrapped is working for deserialization? I just tried it and am getting Could not read JSON: Unrecognized field... errors when I try to deserialize the flattened JSON.

    – E-Riz
    Apr 23 '14 at 18:47


















35















Say I have the following class:



public class Parent {
public int age;
@JsonUnwrapped
public Name name;
}


Producing JSON:



{
"age" : 18,
"first" : "Joey",
"last" : "Sixpack"
}


How do I deserialize this back into the Parent class? I could use @JsonCreator



@JsonCreator
public Parent(Map<String,String> jsonMap) {
age = jsonMap.get("age");
name = new Name(jsonMap.get("first"), jsonMap.get("last"));
}


But this also effectively adds @JsonIgnoreProperties(ignoreUnknown=true) to the Parent class, as all properties map to here. So if you wanted unknown JSON fields to throw an exception, you'd have to do that yourself. In addition, if the map values could be something other than Strings, you'd have to do some manual type checking and conversion. Is there a way for Jackson to handle this case automatically?



Edit:
I might be crazy, but this actually appears to work despite never being explicitly mentioned in the documentation: http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html

I was pretty sure it didn't work for me previously. Still, the proposed @JsonCreator approach might be preferred when custom logic is required to deserialize unwrapped polymorphic types.










share|improve this question




















  • 4





    Are you certain @JsonUnwrapped is working for deserialization? I just tried it and am getting Could not read JSON: Unrecognized field... errors when I try to deserialize the flattened JSON.

    – E-Riz
    Apr 23 '14 at 18:47
















35












35








35


6






Say I have the following class:



public class Parent {
public int age;
@JsonUnwrapped
public Name name;
}


Producing JSON:



{
"age" : 18,
"first" : "Joey",
"last" : "Sixpack"
}


How do I deserialize this back into the Parent class? I could use @JsonCreator



@JsonCreator
public Parent(Map<String,String> jsonMap) {
age = jsonMap.get("age");
name = new Name(jsonMap.get("first"), jsonMap.get("last"));
}


But this also effectively adds @JsonIgnoreProperties(ignoreUnknown=true) to the Parent class, as all properties map to here. So if you wanted unknown JSON fields to throw an exception, you'd have to do that yourself. In addition, if the map values could be something other than Strings, you'd have to do some manual type checking and conversion. Is there a way for Jackson to handle this case automatically?



Edit:
I might be crazy, but this actually appears to work despite never being explicitly mentioned in the documentation: http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html

I was pretty sure it didn't work for me previously. Still, the proposed @JsonCreator approach might be preferred when custom logic is required to deserialize unwrapped polymorphic types.










share|improve this question
















Say I have the following class:



public class Parent {
public int age;
@JsonUnwrapped
public Name name;
}


Producing JSON:



{
"age" : 18,
"first" : "Joey",
"last" : "Sixpack"
}


How do I deserialize this back into the Parent class? I could use @JsonCreator



@JsonCreator
public Parent(Map<String,String> jsonMap) {
age = jsonMap.get("age");
name = new Name(jsonMap.get("first"), jsonMap.get("last"));
}


But this also effectively adds @JsonIgnoreProperties(ignoreUnknown=true) to the Parent class, as all properties map to here. So if you wanted unknown JSON fields to throw an exception, you'd have to do that yourself. In addition, if the map values could be something other than Strings, you'd have to do some manual type checking and conversion. Is there a way for Jackson to handle this case automatically?



Edit:
I might be crazy, but this actually appears to work despite never being explicitly mentioned in the documentation: http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html

I was pretty sure it didn't work for me previously. Still, the proposed @JsonCreator approach might be preferred when custom logic is required to deserialize unwrapped polymorphic types.







java json jackson deserialization






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 15 '13 at 16:35







Shaun

















asked May 15 '13 at 16:13









ShaunShaun

74051537




74051537








  • 4





    Are you certain @JsonUnwrapped is working for deserialization? I just tried it and am getting Could not read JSON: Unrecognized field... errors when I try to deserialize the flattened JSON.

    – E-Riz
    Apr 23 '14 at 18:47
















  • 4





    Are you certain @JsonUnwrapped is working for deserialization? I just tried it and am getting Could not read JSON: Unrecognized field... errors when I try to deserialize the flattened JSON.

    – E-Riz
    Apr 23 '14 at 18:47










4




4





Are you certain @JsonUnwrapped is working for deserialization? I just tried it and am getting Could not read JSON: Unrecognized field... errors when I try to deserialize the flattened JSON.

– E-Riz
Apr 23 '14 at 18:47







Are you certain @JsonUnwrapped is working for deserialization? I just tried it and am getting Could not read JSON: Unrecognized field... errors when I try to deserialize the flattened JSON.

– E-Riz
Apr 23 '14 at 18:47














3 Answers
3






active

oldest

votes


















27














You can use @JsonCreator with @JsonProperty for each field:



@JsonCreator
public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
@JsonProperty("lastName") String lastName) {
this.age = age;
this.name = new Name(firstName, lastName);
}


Jackson does type checking and unknown field checking for you in this case.






share|improve this answer



















  • 2





    Good point. This does answer the question of how to preserve jackson type/field checking in JsonCreators in general, which might be the only useful question remaining. =)

    – Shaun
    May 15 '13 at 16:37



















3














It does work for deserialization as well, although it's not mentioned in the docs explicitly, like you said. See the unit test for deserialization of @JsonUnwrapped here for confirmation - https://github.com/FasterXML/jackson-databind/blob/d2c083a6220f2875c97c29f4823d9818972511dc/src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java#L138






share|improve this answer































    0














    For those who googled here like me, trying to resolve issue when deserializing unwrapepd Map, there is a solution with @JsonAnySetter:



    public class CountryList
    {

    Map<String, Country> countries = new HashMap<>();

    @JsonAnySetter
    public void setCountry(String key, Country value)
    {
    countries.put(key, value);
    }

    }





    share|improve this answer























      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%2f16570073%2fwhats-the-jackson-deserialization-equivalent-of-jsonunwrapped%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      27














      You can use @JsonCreator with @JsonProperty for each field:



      @JsonCreator
      public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
      @JsonProperty("lastName") String lastName) {
      this.age = age;
      this.name = new Name(firstName, lastName);
      }


      Jackson does type checking and unknown field checking for you in this case.






      share|improve this answer



















      • 2





        Good point. This does answer the question of how to preserve jackson type/field checking in JsonCreators in general, which might be the only useful question remaining. =)

        – Shaun
        May 15 '13 at 16:37
















      27














      You can use @JsonCreator with @JsonProperty for each field:



      @JsonCreator
      public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
      @JsonProperty("lastName") String lastName) {
      this.age = age;
      this.name = new Name(firstName, lastName);
      }


      Jackson does type checking and unknown field checking for you in this case.






      share|improve this answer



















      • 2





        Good point. This does answer the question of how to preserve jackson type/field checking in JsonCreators in general, which might be the only useful question remaining. =)

        – Shaun
        May 15 '13 at 16:37














      27












      27








      27







      You can use @JsonCreator with @JsonProperty for each field:



      @JsonCreator
      public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
      @JsonProperty("lastName") String lastName) {
      this.age = age;
      this.name = new Name(firstName, lastName);
      }


      Jackson does type checking and unknown field checking for you in this case.






      share|improve this answer













      You can use @JsonCreator with @JsonProperty for each field:



      @JsonCreator
      public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
      @JsonProperty("lastName") String lastName) {
      this.age = age;
      this.name = new Name(firstName, lastName);
      }


      Jackson does type checking and unknown field checking for you in this case.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered May 15 '13 at 16:27









      hoazhoaz

      7,55543349




      7,55543349








      • 2





        Good point. This does answer the question of how to preserve jackson type/field checking in JsonCreators in general, which might be the only useful question remaining. =)

        – Shaun
        May 15 '13 at 16:37














      • 2





        Good point. This does answer the question of how to preserve jackson type/field checking in JsonCreators in general, which might be the only useful question remaining. =)

        – Shaun
        May 15 '13 at 16:37








      2




      2





      Good point. This does answer the question of how to preserve jackson type/field checking in JsonCreators in general, which might be the only useful question remaining. =)

      – Shaun
      May 15 '13 at 16:37





      Good point. This does answer the question of how to preserve jackson type/field checking in JsonCreators in general, which might be the only useful question remaining. =)

      – Shaun
      May 15 '13 at 16:37













      3














      It does work for deserialization as well, although it's not mentioned in the docs explicitly, like you said. See the unit test for deserialization of @JsonUnwrapped here for confirmation - https://github.com/FasterXML/jackson-databind/blob/d2c083a6220f2875c97c29f4823d9818972511dc/src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java#L138






      share|improve this answer




























        3














        It does work for deserialization as well, although it's not mentioned in the docs explicitly, like you said. See the unit test for deserialization of @JsonUnwrapped here for confirmation - https://github.com/FasterXML/jackson-databind/blob/d2c083a6220f2875c97c29f4823d9818972511dc/src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java#L138






        share|improve this answer


























          3












          3








          3







          It does work for deserialization as well, although it's not mentioned in the docs explicitly, like you said. See the unit test for deserialization of @JsonUnwrapped here for confirmation - https://github.com/FasterXML/jackson-databind/blob/d2c083a6220f2875c97c29f4823d9818972511dc/src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java#L138






          share|improve this answer













          It does work for deserialization as well, although it's not mentioned in the docs explicitly, like you said. See the unit test for deserialization of @JsonUnwrapped here for confirmation - https://github.com/FasterXML/jackson-databind/blob/d2c083a6220f2875c97c29f4823d9818972511dc/src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java#L138







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 27 '18 at 18:56









          spinlokspinlok

          2,493817




          2,493817























              0














              For those who googled here like me, trying to resolve issue when deserializing unwrapepd Map, there is a solution with @JsonAnySetter:



              public class CountryList
              {

              Map<String, Country> countries = new HashMap<>();

              @JsonAnySetter
              public void setCountry(String key, Country value)
              {
              countries.put(key, value);
              }

              }





              share|improve this answer




























                0














                For those who googled here like me, trying to resolve issue when deserializing unwrapepd Map, there is a solution with @JsonAnySetter:



                public class CountryList
                {

                Map<String, Country> countries = new HashMap<>();

                @JsonAnySetter
                public void setCountry(String key, Country value)
                {
                countries.put(key, value);
                }

                }





                share|improve this answer


























                  0












                  0








                  0







                  For those who googled here like me, trying to resolve issue when deserializing unwrapepd Map, there is a solution with @JsonAnySetter:



                  public class CountryList
                  {

                  Map<String, Country> countries = new HashMap<>();

                  @JsonAnySetter
                  public void setCountry(String key, Country value)
                  {
                  countries.put(key, value);
                  }

                  }





                  share|improve this answer













                  For those who googled here like me, trying to resolve issue when deserializing unwrapepd Map, there is a solution with @JsonAnySetter:



                  public class CountryList
                  {

                  Map<String, Country> countries = new HashMap<>();

                  @JsonAnySetter
                  public void setCountry(String key, Country value)
                  {
                  countries.put(key, value);
                  }

                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 21 '18 at 18:48









                  Jan MaresJan Mares

                  494514




                  494514






























                      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%2f16570073%2fwhats-the-jackson-deserialization-equivalent-of-jsonunwrapped%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

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith