0

Let's say I have the following Json data, here I have the id of type integer, and in Java class the type of id is String.

{
  "id": 1,
  "name": "user1"
}
@lombok.Data
@AllArgsConstructor
@NoArgsConstructor
class Data {
    String id;
    String name;
}

I want to convert the Json to the that class while strictly checking if the Json property's value is of same type as the class field.

String json = "{\"id\":1,\"name\":\"user1\"}";
ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());

Data data = objectMapper.readValue(json, Data.class);
System.out.println(data);

Data(id=1, name=user1)

I want that here the conversion shouldn't happen but it gets converted.

1 Answer 1

0

One way I guess is to use a custom deserializer and do a simple type check:

public class CustomDeserializer extends StdDeserializer<String> {

  protected CustomDeserializer() {
    this(null);
  }

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

  @Override
  public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
    if (p.currentToken() != JsonToken.VALUE_STRING) {
      throw new InvalidFormatException(p, "Expected String type", p.getValueAsString(), String.class);
    }
    return p.getValueAsString();
  }
}

And then use that deserializer in the fields you'd like to check:

public class Data {
  @JsonDeserialize(using = CustomDeserializer.class)
  String id;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.