Narasimha
Narasimha

Reputation: 1

Spring boot is automatically converting interger to string

In Postman, I am giving phoneId as a interger, but in javacode(using springboot), i have defined phoneId as a String. When i am hitting the request, i am getting proper response but i am expecting some error. We should handle this before controller

Postman request :

{
    "phoneID": 1
}

Java code :

public class Test {
    private String phoneID;
}

Upvotes: 0

Views: 1310

Answers (1)

Jitendra Tak
Jitendra Tak

Reputation: 96

You could create custom deserializer and annotate your type with @JsonDeserialize annotation.

public class CustomDeserializer extends StdDeserializer<String> {
    protected CustomDeserializer() {
        super(String.class);
    }

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        JsonToken currentToken = jsonParser.getCurrentToken();
        int id = currentToken.id();
        if(id != JsonToken.VALUE_STRING.id()) {
            throw new IOException("Field value is not string json type");
        } else {
            return currentToken.asString();
        }
    }
}

Upvotes: 2

Related Questions