What happens if you annotate a constructor parameter using @JsonProperty, but Json does not specify this property. What value does the constructor get?
For questions like this, I like to just write an example program and see what happens.
The following is an example program.
import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.ObjectMapper; public class JacksonFoo { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); // {"name":"Fred","id":42} String jsonInput1 = "{\"name\":\"Fred\",\"id\":42}"; Bar bar1 = mapper.readValue(jsonInput1, Bar.class); System.out.println(bar1); // output: // Bar: name=Fred, id=42 // {"name":"James"} String jsonInput2 = "{\"name\":\"James\"}"; Bar bar2 = mapper.readValue(jsonInput2, Bar.class); System.out.println(bar2); // output: // Bar: name=James, id=0 // {"id":7} String jsonInput3 = "{\"id\":7}"; Bar bar3 = mapper.readValue(jsonInput3, Bar.class); System.out.println(bar3); // output: // Bar: name=null, id=7 } } class Bar { private String name = "BLANK"; private int id = -1; Bar(@JsonProperty("name") String n, @JsonProperty("id") int i) { name = n; id = i; } @Override public String toString() { return String.format("Bar: name=%s, id=%d", name, id); } }
As a result, the constructor is passed by default to the data type.
How to distinguish a property that has a null value from a property that is not in JSON?
One simple approach would be to check the default deserialization processing, because if the element was present in JSON but had a null value, then a null value would be used to replace any default value specified by the corresponding Java field, For example:
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.annotate.JsonMethod; import org.codehaus.jackson.map.ObjectMapper; public class JacksonFooToo { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
Another approach would be to implement a custom deserializer that checks for the required JSON elements. And another approach would be to write an extension request with Jackson's project at http://jira.codehaus.org/browse/JACKSON
Programmer Bruce Nov 30 '11 at 4:16 2011-11-30 04:16
source share