0

I have this JSON:

{ 
   "label":{    
            "label":"1D812", 
            "version":"01"
           },    
   "productionDate":"140415", 
   "boxNumber":"003",
   "quantity":11000, 
   "order":"0000", 
   "documentId":"DOC-HHS",
   "location":1
}

and I run these commands to create a Box object

ObjectMapper mapper = new ObjectMapper();
Box box = mapper.readValue(myJSON, Box.class);

In Box class there is the following constructor:

public Box(Label label, String productionDate, String boxNumber, int quantity, String order,  String documentId,int location ) {
   this.label = label;
   this.quantity = quantity;
   this.order = order;
   this.boxNumber = boxNumber;
   this.location = location;
   this.documentId = documentId;
   this.productionDate = productionDate;
}

And in Label class I have these constructors (in that order, if it matters)

public Label() {
}    

public Label(String label) {
        this.label = label;
}

public Label(String label, String version) {
    this.label = label;
    this.version = version;
}

public Label(String label, String version, SupplierL supplier) {
    this.label = label;
    this.version = version;
    this.supplier = supplier;
    this.labelWithVersion = label + "-" + version;
}

When I System.out.println(box.toString()); I see that:

Box{label=Label{label=1D812, version=01, supplier=null}, etc...}

I am wondering, why it used the Label constructor with the 3 arguments and not that with the 2?

yaylitzis
  • 5,354
  • 17
  • 62
  • 107
  • I just realized that `System.out.println(box.toString()); ` prints what `toString()` arguments has. Where in my case it has `@Override public String toString() { return "Label{" + "label=" + label + ", version=" + version + ", supplier=" + supplier + '}'; }`.. I got stuck for a moment... – yaylitzis Dec 06 '16 at 12:47

2 Answers2

1

I don't think it calls that 3-arg constructor at all. How would it know what's what? Instead it calls the no-args constructor and set the field values.

If you want it to call a particular constructor, use the @JsonCreator annotation. Note that you can only set it on one.

See this answer for details:

How to deserialize a class with overloaded constructors using JsonCreator

Community
  • 1
  • 1
mprivat
  • 21,582
  • 4
  • 54
  • 64
0

There's no Supplier in your JSON object. So it correcly used 2 argument constructor:

"label":{    
        "label":"1D812", 
        "version":"01"
        }    

And that's exactly what you see in the output:

label=Label{label=1D812, version=01, supplier=null}