Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a blank JSON string value to null for java.lang.String?

Tags:

java

json

jackson

I am trying a simple JSON to de-serialize in to java object. I am however, getting empty String values for java.lang.String property values. In rest of the properties, blank values are converting to null values(which is what I want).

My JSON and related Java class are listed below.

JSON string:

{   "eventId" : 1,   "title" : "sample event",   "location" : ""  } 

EventBean class POJO:

public class EventBean {      public Long eventId;     public String title;     public String location;  } 

My main class code:

ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);  try {     File file = new   File(JsonTest.class.getClassLoader().getResource("event.txt").getFile());      JsonNode root = mapper.readTree(file);     // find out the applicationId      EventBean e = mapper.treeToValue(root, EventBean.class);     System.out.println("It is " + e.location); } 

I was expecting print "It is null". Instead, I am getting "It is ". Obviously, Jackson is not treating blank String values as NULL while converting to my String object type.

I read somewhere that it is expected. However, this is something I want to avoid for java.lang.String too. Is there a simple way?

like image 655
Mayur Avatar asked Jun 15 '15 09:06

Mayur


People also ask

Can JSON string null?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

Can JSON have null keys?

JSON has two types of null valueWhen the key is provided, and the value is explicitly stated as null . When the key is not provided, and the value is implicitly null .

How do you serialize and deserialize JSON object in Java?

Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished. Program output.

How do I ignore null values in JSON Deserializing?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.


2 Answers

Jackson will give you null for other objects, but for String it will give empty String.

But you can use a Custom JsonDeserializer to do this:

class CustomDeserializer extends JsonDeserializer<String> {      @Override     public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {         JsonNode node = jsonParser.readValueAsTree();         if (node.asText().isEmpty()) {             return null;         }         return node.toString();     }  } 

In class you have to use it for location field:

class EventBean {     public Long eventId;     public String title;      @JsonDeserialize(using = CustomDeserializer.class)     public String location; } 
like image 72
Sachin Gupta Avatar answered Sep 20 '22 10:09

Sachin Gupta


It is possible to define a custom deserializer for the String type, overriding the standard String deserializer:

this.mapper = new ObjectMapper();  SimpleModule module = new SimpleModule();  module.addDeserializer(String.class, new StdDeserializer<String>(String.class) {      @Override     public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {         String result = StringDeserializer.instance.deserialize(p, ctxt);         if (StringUtils.isEmpty(result)) {             return null;         }         return result;     } });  mapper.registerModule(module); 

This way all String fields will behave the same way.

like image 45
jgesser Avatar answered Sep 22 '22 10:09

jgesser