Home > Blockchain >  Json - Serializing Property in the response as a Different Type
Json - Serializing Property in the response as a Different Type

Time:10-23

I have a String field in my POJO like this:

private String code; // code can be "111", "CD", "XX", etc.

Is there some JSON annotation that would allow serializing this field as Number (i.e. int), but only if the property can be converted from String into int?

Example

If code is number, expected response:

{
    "code": 111
}

Else, if it is text:

{
    "code": "CD"
}

Right now both come out as string "111", "CD", etc.

CodePudding user response:

You can implement a custom serializer by extending abstract class JsonSerializer, and provide it via using attribute of the @JsonSerialize annotation, placed on the code field.

To discriminate between the cases when property can be represented as an int you can use a regular expression "\\d ".

Example:

public class Foo {
    @JsonSerialize(using = StringToIntSerializer.class)
    private String code;
    // other fields
    
    // getter, setters, etc.
}

public static class StringToIntSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String value, JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
    
        if (value.matches("\\d ")) gen.writeNumber(value);
        else gen.writeString(value);
    }
}
  • Related