1

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

shaya ajzner
  • 179
  • 1
  • 9
  • @Jens I would have thought so, too, but I just checked [the grammar](https://www.json.org/json-en.html), and the empty string matches the key for `members`. – chrylis -cautiouslyoptimistic- Nov 08 '21 at 05:48
  • Have you seen this post [How to deserialize empty strings with jackson?](https://stackoverflow.com/questions/50251828/how-to-deserialize-empty-strings-with-jackson)? – LHCHIN Nov 08 '21 at 08:20
  • Yes. It talks about enums. I wasn't able to apply to my case... I just want the object to be serialised. Just treat the empty string like any other string. make sense? – shaya ajzner Nov 08 '21 at 08:37

1 Answers1

1

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.

LHCHIN
  • 3,679
  • 2
  • 16
  • 34