1

I like to deserialize with Jackson an empty String member ("") to null. The Deserialization Feature "ACCEPT_EMPTY_STRING_AS_NULL_OBJECT" can for this unfortunately not be used (see link).

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class Supplier  {
   private Integer id;
   private String name;
   private String image;
   private String link;
   private String description;
}

So after deserialization of the following JSON String the string members "link" and "image" should be null and not "".

  {"id":37,"name":"Life","image":"","link":"","description":null}

I am looking for a way to write an own deserializer which can be used for String members of a POJO. Is there a way to achieve this? I am using faster Jackson 2.6.0.

Community
  • 1
  • 1
megloff
  • 1,400
  • 4
  • 27
  • 44

1 Answers1

0

The custom deserializer can be done as follows in Jackson 2.6.0.

public class SupplierDeserializer extends JsonDeserializer<Supplier> {

    @Override
    public Supplier deserialize(JsonParser jp, DeserializationContext context) throws IOException, JsonProcessingException {
        Supplier sup = new Supplier();

        JsonNode node = jp.readValueAsTree();

        sup.setId(node.get("id").asInt());

        sup.setDescription(node.get("description").asText());

        String image = node.get("image").asText();
        if("".equals(image)) {
            image = null;
        }
        sup.setImage(image);

        String link = node.get("link").asText();
        if("".equals(link)) {
            link = null;
        }
        sup.setLink(link);

        sup.setName(node.get("name").asText());

        return sup;
    }
}

Register the custom deserialiser with the Supplier class

@JsonDeserialize(using = SupplierDeserializer.class)
public class Supplier {
    private Integer id;
    private String name;
    private String image;
    private String link;
    private String description;

    // getters and setters
}

Call the ObjectMapper class to parse the JSON data

String jsonData = "{\"id\":37,\"name\":\"Life\",\"image\":\"\",\"link\":\"\",\"description\":null}";

Supplier sup = new ObjectMapper().readValue(jsonData, Supplier.class);
Dukefirehawk
  • 476
  • 1
  • 3
  • 11
  • Thank you, but can this be done more generic? i.e. for all my POJOs and they string members? I am looking for something like adding a generic "deserializer" to the object mapper [link](http://apieceofmycode.blogspot.ch/2015/05/json-jackson-custom-deserializer-to.html) but I had no luck to get it working for my problem. – megloff Feb 05 '16 at 08:09