简体   繁体   中英

Jackson - Deserialize empty String Member to null

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM