shaya ajzner
shaya ajzner

Reputation: 179

Jackson include a key that is empty string

I accept from a server a json like this:

{
  "": "hello"
}

And in Jackson I did

@JsonProperty("")

private String string

When deserialising the object it ignores the property completely. How can I make an empty string count as a key?

Thank you

Upvotes: 1

Views: 814

Answers (1)

LHCHIN
LHCHIN

Reputation: 4009

I found a way to achieve what you want with custom deserializer by following steps.

Step 1: Create the POJO class you want to deserialize to

public class MyPojo {
    private String emptyFieldName;

    //constructor, getter, setter and toString
}

Step 2: Create your custom deserializer

public class MyDeserializer extends StdDeserializer<MyPojo> {
    public MyDeserializer () {
        this(null);
    }

    protected MyDeserializer (Class<?> vc) {
        super(vc);
    }

    @Override
    public MyObject deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        String emptyFieldName = jsonNode.get("").asText();

        return new MyPojo(emptyFieldName);
    }
}

Step 3: Register this custom deserializer

ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(MyPojo.class, new MyDeserializer());
objectMapper.registerModule(module);

MyPojo myPojo = objectMapper.readValue(jsonStr, MyPojo.class);
System.out.println(myPojo.getEmptyFieldName());

Console output:

hello


BTW, you could also directly register this custom deserializer on the class:

@JsonDeserialize(using = MyDeserializer.class)
public class MyPojo {
    ...
}

For more information, please refer to Getting Started with Custom Deserialization in Jackson.

Upvotes: 1

Related Questions