Asked  7 Months ago    Answers:  5   Viewed   146 times

How can Jackson be configured to ignore a field value during serialization if that field's value is null.

For example:

public class SomeClass {
   // what jackson annotation causes jackson to skip over this value if it is null but will 
   // serialize it otherwise 
   private String someValue; 
}

 Answers

16

To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.

A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.

Tuesday, June 1, 2021
 
cbcp
answered 7 Months ago
99

You should use the @JsonProperty on the field you want to change the default name mapping.

class User{
    @JsonProperty("first_name")
    protected String firstName;
    protected String getFirstName(){return firstName;}
}

For more info: the API

Wednesday, June 2, 2021
 
muaddhib
answered 7 Months ago
83

I would use a JsonDeserializer. Inspect the field in question, determine, if it is emtpy and return null, so your ContainedObject would be null.

Something like this (semi-pseudo):

 public class MyDes extends JsonDeserializer<ContainedObject> {

        @Override
        public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
            //read the JsonNode and determine if it is empty JSON object
            //and if so return null

            if (node is empty....) {
                return null;
            }
            return node;
        }

    }

then in your model:

 public class Entity {
    private long id;
    private String description;

    @JsonDeserialize(using = MyDes.class)
    private ContainedObject containedObject;

   //Contructor, getters and setters omitted

 }

Hope this helps!

Friday, June 25, 2021
 
relipse
answered 6 Months ago
24

You need to create and use a custom serializer.

public class ItemTypeSerializer extends JsonSerializer<ItemType> 
{
    @Override
    public void serialize(ItemType value, JsonGenerator jgen, 
                    SerializerProvider provider) 
                    throws IOException, JsonProcessingException 
    {
        jgen.writeString(value.name);
    }

}

@JsonSerialize(using = ItemTypeSerializer.class)
class ItemType
{
    String name;
    int somethingElse;
}
Saturday, September 18, 2021
 
jonboy
answered 3 Months ago
58

Update:

Just add a @JsonFormat annotation with the date format above the Instant property. It's very easy.

In the case you have an ObjectMapper with the JavaTimeModule like next:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

If you have a class with an Instant property, you should add the @JsonFormat annotation and put the date pattern which hasn't milliseconds. It would be like next:

public static class TestDate {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss", timezone = "UTC")
    Instant instant;

    //getters & setters
}

So if you serialize an object to Json it works perfectly:

String json = mapper.writeValueAsString(testDate);
System.out.println(json); 

Output

{"instant":"2016-11-10 06:03:06"}


Old Answer. I don't know why but It doesn't work properly:

You could use the Jackson2ObjectMapperBuilder to build it.

You just need to add the dateFormat you want. It would be something like next:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

ObjectMapper mapper = Jackson2ObjectMapperBuilder
            .json()       
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) 
            .modules(new JavaTimeModule())
            .dateFormat(dateFormat)
            .build();
Thursday, October 7, 2021
 
jbowman
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share