Rectangle 27 28

It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {} but your JSON actually starts with square brackets [] designating an array.

List<product>
TypeReference
myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});

A couple of other notes: your classes should always be CamelCased. Your main method can just be public static void main(String[] args) throws Exception which saves you all the useless catch blocks.

jackson deserialization json to java-objects - Stack Overflow

java json object jackson deserialization
Rectangle 27 13

It works with jackson 2.0!!

Seems if you don't put the visible to true in this case it wont work....can you confirm?

I can confirm that visible needs to be true to work. In my case I also used include = JsonTypeInfo.As.EXISTING_PROPERTY to avoid the property appearing twice during serialization.

java - Jackson Polymorphic Deserialization based on Enum - Stack Overf...

java json polymorphism jackson
Rectangle 27 9

You have to change the line

product userFromJSON = mapper.readValue(userDataJSON, product.class);
product[] userFromJSON = mapper.readValue(userDataJSON, product[].class);

since you are deserializing an array (btw: you should start your class names with upper case letters as mentioned earlier). Additionally you have to create setter methods for your fields or mark them as public in order to make this work.

Edit: You can also go with Steven Schlansker's suggestion and use

List<product> userFromJSON =
        mapper.readValue(userDataJSON, new TypeReference<List<product>>() {});

instead if you want to avoid arrays.

jackson deserialization json to java-objects - Stack Overflow

java json object jackson deserialization
Rectangle 27 6

JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"

 System.out.println("id : "+node.findValues("id").get(0).asText());

this also done the trick.

jackson deserialization json to java-objects - Stack Overflow

java json object jackson deserialization
Rectangle 27 26

You can write custom deserializer for this class. It could look like this:

class FlickrAccountJsonDeserializer extends JsonDeserializer<FlickrAccount> {

    @Override
    public FlickrAccount deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        Root root = jp.readValueAs(Root.class);

        FlickrAccount account = new FlickrAccount();
        if (root != null && root.user != null) {
            account.setId(root.user.id);
            if (root.user.username != null) {
                account.setUsername(root.user.username.content);
            }
        }

        return account;
    }

    private static class Root {

        public User user;
        public String stat;
    }

    private static class User {

        public String id;
        public UserName username;
    }

    private static class UserName {

        @JsonProperty("_content")
        public String content;
    }
}

After that, you have to define serializer for your class. You can do this in this way:

@JsonDeserialize(using = FlickrAccountJsonDeserializer.class)
class FlickrAccount {
    ...
}

Thank you. The part that I was missing in this was the annotation. I had to supply the @JsonDeserialize annotation despite the object being a subclass of a type registered in a module.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - Custom JSON Deserialization with Jackson - Stack Overflow

java json jackson flickr
Rectangle 27 2

Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

As a side note: You should use Pascal casing for your class names. That is Product, and not product.

@ Esteban Araya i have tried this yet same error occurs

jackson deserialization json to java-objects - Stack Overflow

java json object jackson deserialization
Rectangle 27 23

An example taken from TestRootName.java in https://github.com/FasterXML/jackson-databind may give a better way of doing this. Specifically using withRootName(""):

private ObjectMapper rootMapper()
{
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
    mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    return mapper;
}

public void testRootUsingExplicitConfig() throws Exception
{
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writer().withRootName("wrapper");
    String json = writer.writeValueAsString(new Bean());
    assertEquals("{\"wrapper\":{\"a\":3}}", json);

    ObjectReader reader = mapper.reader(Bean.class).withRootName("wrapper");
    Bean bean = reader.readValue(json);
    assertNotNull(bean);

    // also: verify that we can override SerializationFeature as well:
    ObjectMapper wrapping = rootMapper();
    json = wrapping.writer().withRootName("something").writeValueAsString(new Bean());
    assertEquals("{\"something\":{\"a\":3}}", json);
    json = wrapping.writer().withRootName("").writeValueAsString(new Bean());
    assertEquals("{\"a\":3}", json);

    bean = wrapping.reader(Bean.class).withRootName("").readValue(json);
    assertNotNull(bean);
}

Jackson json deserialization, ignore root element from json - Stack Ov...

json jackson
Rectangle 27 5

Since I don't want to implement a custom class (Username) just to map the username, I went with a little bit more elegant, but still quite ugly approach:

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(in);
JsonNode user = node.get("user");
FlickrAccount account = new FlickrAccount();
account.setId(user.get("id").asText());
account.setUsername(user.get("username").get("_content").asText());

It's still not as elegant as I hoped, but at least I got rid of all the ugly casting. Another advantage of this solution is, that my domain class (FlickrAccount) is not polluted with any Jackson annotations.

Based on @Micha Ziober's answer, I decided to use the - in my opinion - most straight forward solution. Using a @JsonDeserialize annotation with a custom deserializer:

@JsonDeserialize( using = FlickrAccountDeserializer.class )
public class FlickrAccount {
    ...
}

But the deserializer does not use any internal classes, just the JsonNode as above:

class FlickrAccountDeserializer extends JsonDeserializer<FlickrAccount> {
    @Override
    public FlickrAccount deserialize(JsonParser jp, DeserializationContext ctxt) throws 
            IOException, JsonProcessingException {
        FlickrAccount account = new FlickrAccount();
        JsonNode node = jp.readValueAsTree();
        JsonNode user = node.get("user");
        account.setId(user.get("id").asText());
        account.setUsername(user.get("username").get("_content").asText());
        return account;
    }
}

java - Custom JSON Deserialization with Jackson - Stack Overflow

java json jackson flickr
Rectangle 27 12

JsonNode jsonNode = mapper.readValue(s, JsonNode.class); 
JsonNode userCards = jsonNode.path("data");
List<Item> list = mapper.readValue(userCards.toString(), new TypeReference<List<Item>>(){});

This answer would be much better if you included some text with it to explain how and why it addresses the issue.

I found this approach preferable to that by StaxMan. Reason being is that StaxMan's requires an extra object to wrap the array/list. This approach only requires an extra line. I rewrote my code slightly differently from maziar's, eliminates an extra line. See my answer, though it's just a variant of maziar's.

@awoodland : someone can probably explain better than me; but, in simple terms, the problem is that the OP's JSON isn't a single object of type Item, it's an array/list of Items. You've got to tell Jackson to expect a list, not an object. See my answer below, which is simpler, and it might make more sense to you. Converting to a JsonNode first works, but seems superfluous (AFAIK). I could be wrong though, maybe something is missing in the output. Seems to work for me though.

android jackson json object mapper array deserialization - Stack Overf...

android json jackson pojo
Rectangle 27 10

I experienced a similar problem developing a restful application in Spring. I had to support a very heterogeneous API, some of it had root elements, another did not. I could not find a better solution than to configure this property realtime. It's a great pity there is no support for per-class root element unwrapping in Jackson. Anyway, somebody may find this helpful.

@Component
public class ObjectMapper extends com.fasterxml.jackson.databind.ObjectMapper {
    private void autoconfigureFeatures(JavaType javaType) {
        Annotation rootAnnotation = javaType.getRawClass().getAnnotation(JsonRootName.class);
        this.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, rootAnnotation != null);
    }

    @Override
    protected Object _readMapAndClose(JsonParser jsonParser, JavaType javaType) throws IOException, JsonParseException, JsonMappingException {
        autoconfigureFeatures(javaType);
        return super._readMapAndClose(jsonParser, javaType);
    }

}

Jackson json deserialization, ignore root element from json - Stack Ov...

json jackson
Rectangle 27 60

I've searched a lot and the best way I've found so far is on this article:

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

com.fasterxml.jackson.databind.JsonDeserializer
asText()
getTextValue()
:)

I've got NPE on "oc.readTree" with that approach. Does anybody know how to handle it?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - Right way to write JSON deserializer in Spring or extend it - S...

java json spring jackson deserialization
Rectangle 27 8

Your example is missing couple of pieces (esp. definition of Item), to know if your structure is compatible; but in general JSON and Object structures need to match. So, you would at least need something like:

public class DataWrapper {
  public List<Item> data; // or if you prefer, setters+getters
}

and if so, you would bind with:

DataWrapper wrapper = mapper.readValue(json, DataWrapper.class);

and access data as

List<Item> items = wrapper.data;

android jackson json object mapper array deserialization - Stack Overf...

android json jackson pojo
Rectangle 27 18

One possible approach is to sub-class JacksonAnnotationIntrospector, override method(s) that introspect ignorability of methods (and/or fields) to use whatever logic you want.

It might also help if you gave an example of practical application, i.e what and why you are trying to prevent from being deserialized.

Here is an explanation: jroller.com/RickHigh/entry/filtering_json_feeds_from_spring I don't use Roo and aspectj code give error at my Intellij IDEA8(thisJoinPoint and proceed methods can not recognized). It would be great if I could implement it as annotation as like described.

I have a Spring 3 REST application. I have a bean at my server side and I list them at client. However it has many fields and I dn't list every field of my bean at table. However at another page I list all the fields of my bean at another table. So my purpose is that I don't want to send all information to client side for efficiency.

Ok: but just to be clear -- when sending things, you are generally talking about serialization; deserialization is the reverse (reading JSON into objects). So perhaps you are looking for serialization feature instead? If so, link I mentioned would be very useful?

java - Jackson Change JsonIgnore Dynamically - Stack Overflow

java json deserialization jackson
Rectangle 27 34

Of course there is an automated way called serialization and deserialization and you can define it with specific annotations (@JsonSerialize,@JsonDeserialize) as mentioned by pb2q as well.

You can use both java.util.Date and java.util.Calendar ... and probably JodaTime as well.

The @JsonFormat annotations not worked for me as I wanted

@JsonFormat(locale = "hu", shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm", timezone = "CET")

@JsonFormat(locale = "hu", shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm", timezone = "Europe/Budapest")

You need to use custom serializer and custom deserializer instead of the @JsonFormat annotation if you want predicted result.

public class CustomCalendarSerializer extends JsonSerializer<Calendar> {

    public static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static final Locale LOCALE_HUNGARIAN = new Locale("hu", "HU");
    public static final TimeZone LOCAL_TIME_ZONE = TimeZone.getTimeZone("Europe/Budapest");

    @Override
    public void serialize(Calendar value, JsonGenerator gen, SerializerProvider arg2)
            throws IOException, JsonProcessingException {
        if (value == null) {
            gen.writeNull();
        } else {
            gen.writeString(FORMATTER.format(value.getTime()));
        }
    }
}
public class CustomCalendarDeserializer extends JsonDeserializer<Calendar> {

    @Override
    public Calendar deserialize(JsonParser jsonparser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        String dateAsString = jsonparser.getText();
        try {
            Date date = CustomCalendarSerializer.FORMATTER.parse(dateAsString);
            Calendar calendar = Calendar.getInstance(
                CustomCalendarSerializer.LOCAL_TIME_ZONE, 
                CustomCalendarSerializer.LOCALE_HUNGARIAN
            );
            calendar.setTime(date);
            return calendar;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

and the usage of the above classes:

public class CalendarEntry {

    @JsonSerialize(using = CustomCalendarSerializer.class)
    @JsonDeserialize(using = CustomCalendarDeserializer.class)
    private Calendar calendar;

    // ... additional things ...
}

Using this implementation the execution of the serialization and deserialization process consecutively results the origin value.

Only using the @JsonFormat annotation the deserialization gives different result I think because of the library internal timezone default setup what you can not change with annotation parameters (that was my experience with Jackson library 2.5.3 and 2.6.3 version as well).

I have got downvote for my answer yesterday. I worked a lot on this topic so I do not understand. May I have got some feedback to learn from it? I would appreciate some notes in case of downvote. This way we can learn more from each other.

Great answer, thanks it really helped me! Minor suggestion - consider putting CustomCalendarSerializer and CustomCalendarDeserializer as static classes within an enclosing parent class. I think this would make the code a little nicer :)

@Stuart - you should simply offer this reorganisation of the code as another answer, or propose an edit. Miklos may not have the time free to do it.

@MiklosKrivan I have downvoted you for several reasons. You should know that SimpleDateFormat is not threadsafe and frankily you should use alternative libraries for date formatting (Joda, Commons-lang FastDateFormat etc). The other reason is the setting of the timezone and even locale. It is far more preferable to use GMT in serialization environment and let your client say which timezone it is in or even attach the preferred tz as a separate string. Set your server to be on GMT aka UTC. Jackson has builtin ISO format.

Thx @AdamGent for your feedback. I understand and accept your suggestions. But in this particular case I just wanted to focus that the JsonFormat annotation with locale information is not working the way we would expect. And how can be solved.

java - Date format Mapping to JSON Jackson - Stack Overflow

java json date jackson pojo
Rectangle 27 22

You can implement a custom JsonDeserializer for your generic type which also implements ContextualDeserializer.

For example, suppose we have the following simple wrapper type that contains a generic value:

public static class Wrapper<T> {
    public T value;
}
{
    "name": "Alice",
    "age": 37
}

into an instance of a class that looks like this:

public static class Person {
    public Wrapper<String> name;
    public Wrapper<Integer> age;
}

Implementing ContextualDeserializer allows us to create a specific deserializer for each field in the Person class, based on the generic type parameters of the field. This allows us to deserialize the name as a string, and the age as an integer.

public static class WrapperDeserializer extends JsonDeserializer<Wrapper<?>> implements ContextualDeserializer {
    private JavaType valueType;

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        JavaType wrapperType = property.getType();
        JavaType valueType = wrapperType.containedType(0);
        WrapperDeserializer deserializer = new WrapperDeserializer();
        deserializer.valueType = valueType;
        return deserializer;
    }

    @Override
    public Wrapper<?> deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
        Wrapper<?> wrapper = new Wrapper<>();
        wrapper.value = ctxt.readValue(parser, valueType);
        return wrapper;
    }
}

It is best to look at createContextual here first, as this will be called first by Jackson. We read the type of the field out of the BeanProperty (e.g. Wrapper<String>) and then extract the first generic type parameter (e.g. String). We then create a new deserializer and store the inner type as the valueType.

Once deserialize is called on this newly created deserializer, we can simply ask Jackson to deserialize the value as the inner type rather than as the whole wrapper type, and return a new Wrapper containing the deserialized value.

In order to register this custom deserializer, we then need to create a module that contains it, and register that module:

SimpleModule module = new SimpleModule()
        .addDeserializer(Wrapper.class, new WrapperDeserializer());

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);

If we then try to deserialize the example JSON from above, we can see that it works as expected:

Person person = objectMapper.readValue(json, Person.class);
System.out.println(person.name.value);  // prints Alice
System.out.println(person.age.value);   // prints 37

There are some more details about how contextual deserializers work in the Jackson documentation.

Thank you for this post. Incredibly helpful to achieve what I wanted. I have made a few alterations that works with root values in case anyone else from Google comes around. gist.github.com/darylteo/a7be65b539c0d8d3ca0de94d96763f33

Thank you, that really helped The contextual type itself could be generic, in that case property will be null, you need to create the JsonDeserializer using the ctxt.getContextualType

java - How to create a custom deserializer in Jackson for a generic ty...

java json generics jackson deserialization
Rectangle 27 5

@JsonDeserialize(using = ThingDeseralizer.class)

This will tell Jackson how to deserialze that particular field, rest all will go as default.

Yes I just discovered this. Hypothetically speaking is there a way to do this with a single deserializer on the class? I imagine there has to be some method on the super class, or a different class to extend, that will fill out everything and let me override just what I want.

You mean to use deserializer on whole class? Than as you said you have to define all fields. But that's easy too, check this answer: link

what's the relevant part in that link?

@hvgotcodes For serialization, JsonSerializable interface would do this, but unfortunately deserialization does not have similar support -- this is due to difficulties in defining suitable API: during serialization there is already an instance to call method on, but this is not the case for deserialization.

@hvgotcodes That custom ItemSerializer class to serialize the whole Item class. It's easy to serialize integer, string etc.

json - Jackson Deserializer for one custom field? - Stack Overflow

json jackson deserialization
Rectangle 27 5

I am a complete newbie with Jackson, but the following works for me.

public class A {
    private String a1;
    private Integer a2;
    public String getA1() { return a1; }
    public Integer getA2() { return a2; }
    public void setA1(String a1) { this.a1 = a1; }
    public void setA2(Integer a2) { this.a2 = a2; }

    @JsonCreator
    public static A fromJSON(String val) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        A a = mapper.readValue(val,A.class);
        return a;
    }
}

That alone solves the deserialization problem. The harder part for me was the correct serialization of the keys. What I did there was to define a key serializer that serializes named classes as there JSON serialization, like this:

public class KeySerializer extends SerializerBase<Object> {
    private static final SerializerBase<Object> DEFAULT = new StdKeySerializer();

    private Set<Class<?>> objectKeys_ = Collections.synchronizedSet(new HashSet<Class<?>>());

    protected KeySerializer(Class<?>... objectKeys) {
        super(Object.class);
        for(Class<?> cl:objectKeys) {
            objectKeys_.add(cl);
        }
    }


    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException {
        return DEFAULT.getSchema(provider, typeHint);
    }


    @Override
    public void serialize(Object value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonGenerationException {
        if (objectKeys_.contains(value.getClass())) {
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, value);
            jgen.writeFieldName(writer.toString());
        } else {
            DEFAULT.serialize(value, jgen, provider);
        }
    }
}

Then to prove it works, serializing and deserializing an instance of class C:

ObjectMapper mapper = new ObjectMapper();
    StdSerializerProvider provider = new StdSerializerProvider();
    provider.setKeySerializer(new KeySerializer(A.class));
    mapper.setSerializerProvider(provider);

    StringWriter out = new StringWriter();
    mapper.writeValue(out, c);
    String json = out.toString();
    System.out.println("JSON= "+json);

    C c2 = mapper.readValue(json, C.class);
    System.out.print("C2= ");
    StringWriter outC2 = new StringWriter();
    mapper.writeValue(outC2, c2);
    System.out.println(outC2.toString());
JSON= {"c1":"goo","map":{"{\"a1\":\"1ccf\",\"a2\":7376}":{"b1":"5ox"},"{\"a1\":\"1cd2\",\"a2\":7379}":{"b1":"5p0"},"{\"a1\":\"1cd5\",\"a2\":7382}":{"b1":"5p3"},"{\"a1\":\"1cd8\",\"a2\":7385}":{"b1":"5p6"}}}
C2= {"c1":"goo","map":{"{\"a1\":\"1ccf\",\"a2\":7376}":{"b1":"5ox"},"{\"a1\":\"1cd2\",\"a2\":7379}":{"b1":"5p0"},"{\"a1\":\"1cd5\",\"a2\":7382}":{"b1":"5p3"},"{\"a1\":\"1cd8\",\"a2\":7385}":{"b1":"5p6"}}}

I feel there ought to have been a better way of doing saying how to serialize the key by using annotations, but I could not work it out.

I will try to merge this solution with what I'm trying to do with StdKeyDeserializer and see if I find a better way.

I used your solution, the only different thing is that I implemented the serialize method without using the objectKeys attribute. My implementation is exactly the four lines that you have inside if block. Now I'm having problems with Period joda-time's class, but I will make a new post with that one. Thanks, Simon.

json - how to create a custom JsonDeserializer in Java? - Stack Overfl...

java json jackson deserialization
Rectangle 27 4

You can put a @JsonUnwrapped annotation on the Address field in the customer class. Here is an example:

public class JacksonValue {
    final static String JSON = "{\n"
            +"   \"code\":\"C001\",\n"
            +"   \"city\": \"Pune\",\n"
            +"   \"street\": \"ABC Road\"\n"
            +"}";

    static class Address {
        public String city;
        public String street;

        @Override
        public String toString() {
            return "Address{" +
                    "city='" + city + '\'' +
                    ", street='" + street + '\'' +
                    '}';
        }
    }

    static class Customer {
        public String code;
        @JsonUnwrapped
        public Address address;

        @Override
        public String toString() {
            return "Customer{" +
                    "code='" + code + '\'' +
                    ", address=" + address +
                    '}';
        }
    }


    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(JSON, Customer.class));
    }
}
Customer{code='C001', address=Address{city='Pune', street='ABC Road'}}

json - Jackson Deserialization of Embedded Java Object - Stack Overflo...

java json jackson deserialization
Rectangle 27 4

@JsonDeserialize(using = ThingDeseralizer.class)

This will tell Jackson how to deserialze that particular field, rest all will go as default.

Yes I just discovered this. Hypothetically speaking is there a way to do this with a single deserializer on the class? I imagine there has to be some method on the super class, or a different class to extend, that will fill out everything and let me override just what I want.

You mean to use deserializer on whole class? Than as you said you have to define all fields. But that's easy too, check this answer: link

what's the relevant part in that link?

@hvgotcodes For serialization, JsonSerializable interface would do this, but unfortunately deserialization does not have similar support -- this is due to difficulties in defining suitable API: during serialization there is already an instance to call method on, but this is not the case for deserialization.

@hvgotcodes That custom ItemSerializer class to serialize the whole Item class. It's easy to serialize integer, string etc.

json - Jackson Deserializer for one custom field? - Stack Overflow

json jackson deserialization
Rectangle 27 6

  • @JsonIgnoreProperties(ignoreUnknown=true) is applicable at deserialization of JSON to Java object (POJO) only. If your POJO does not contain certain properties which JSON does contain, they are ignored and no error is thrown.

On the other hand @JsonInclude(Include.NON_EMPTY) is used at serialization of POJO to JSON and it says, skip POJO properties that are:

null or what is considered empty are not to be included. Definition of emptiness is data type specific.

Is used at serialization time only. It says that if value of a property (or all properties) in question is equal to certain value (null, empty - whatever that means, or a default value) this property is not serialized.

Without this annotation property value is always serialized. The annotation helps to reduce number of transferred properties (Property default value must be specified when it is not present on receiving side).

{"firstName":"Mark","middleName":null,"lastName":"Watney"}

But if Person is annotated with @JsonInclude(Include.NON_EMPTY), middleName is omitted from the output because its value is "empty" (null in this case):

@JsonInclude(Include.NON_EMPTY)
public static class Person {
    [....]
}
{"firstName":"Mark","lastName":"Watney"}

Is used to ignore certain properties in serialization and deserialization regardless of its values:

to prevent specified fields from being serialized or deserialized (i.e. not include in JSON output; or being set even if they were included): @JsonIgnoreProperties({ "internalId", "secretKey" })

{
    "firstName": "Homer",
    "middleName": "Jay",
    "lastName": "Simpson"
}
public class Person {
    public String firstName;
    public String lastName;
}
mapper.readValue(json, Person.class)
UnrecognizedPropertyException

Because property middleName is not part of Person class.

Person
@JsonIgnoreProperties(ignoreUnknown=true)
middleName
@JsonIgnoreProperties(ignoreUnknown=true)
public class person {
    [...]
}

Another common use case is to suppress serialization of sensitive properties, like for example password:

@JsonIgnoreProperties("password")
public static class User {
    public String login = "simpsonh";
    public String password = "D00nut";
    public String firstName = "Homer";
    public String middleName = "Jay";
    public String lastName = "Simpson";
}

Now if you serialize User class , password will be omitted from the output:

User u = new User();
System.out.println(mapper.writeValueAsString(u));
{"login":"simpsonh","firstName":"Homer","middleName":"Jay","lastName":"Simpson"}

You are welcome :) !

serialization - Jackson Annotations: Difference Between JsonIgnoreProp...

serialization jackson deserialization