On Wed, Apr 1, 2020 at 5:24 PM maxxyme _ <[email protected]> wrote:
>
> Hello,
>
> I already posted a question on SO but unfortunately didn't get any relevant 
> answer (just one, and the guy told he's not keen on @JsonCreator...)
> Everything's detailed there (Java classes & call code):
> https://stackoverflow.com/questions/60132067/cant-properly-deserialize-json-using-jsoncreator-as-described-in-the-javadoc
>
> If someone's willing to point me to what's wrong with my class definitions, 
> esp. with the 2 distinct exceptions:
> - I don't understand the 1st one (why doesn't it works...?)
> - For what I understand from the 2nd, Jackson tries to deserialize the whole 
> JSON as for the Inner object... but why?

Because there are 2 different possibilities of what might be expected.

POJO1: expect JSON Object with same properties as POJO:

public class Pojo1 {
   public int x, y;

   @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
   public Pojo(@JsonProperty("x") int x0, @JsonProperty("y") int y0) {
      x = x0;
      y = y0;
   }
}

JSON that can be read: {"x":1, "y":2}

POJO 2: expect JSON _value_ that is used to construct POJO, but is not
property-based (often not JSON Object, but may be)

public class Pojo2 {
   int x, y;

  @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
  public Pojo2(/* Note: NO property name */ int[] args) {
     x = args[0];
     y = args[1];
  }
}

JSON that can be read: [1, 2]

-------------

So far so good? One thing to note is that "delegating" style is only
applicable with just one parameter for constructor (or factory
method); whereas "properties" style works for any number.

But this means that the special case of 1 argument constructor (or
factory method) can be ambiguous if `mode` is not specified. With
this:

class NameBean {
   private String name;

   @JsonCreator
   public NameBean(String name) {
       this.name = name;
   }
}

which JSON should this map to/from:

{ "name" : "Bob" }

OR

"Bob"

?

There is no good way to figure out that I am aware of. Heuristics
fail; and as the answer at SO mentioned, parameter names for
constructors may or may not be included even on Java 8 (and were never
included before that; Jackson still only requires Java 7 for
databind).

This is why you need to either add the `mode` property OR add explicit
`@JsonProperty` for constructor parameter if you want to force
Properties-style Creator.
And if conversely you want delegating style, mode.

I hope this helps,

-+ Tatu +-

-- 
You received this message because you are subscribed to the Google Groups 
"jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/jackson-user/CAL4a10gWrj8vSTc8S5MSbEOrjF%3DyVhYnrThY2u1yKPxmhzoU4g%40mail.gmail.com.

Reply via email to