Home  >  Article  >  Check the type of Json property value when converted to Java class

Check the type of Json property value when converted to Java class

WBOY
WBOYforward
2024-02-22 14:16:06486browse

php editor Youzi brings you the Java Q&A topic of this article: "Checking the type of Json attribute value when converting to a Java class". During the development process, we often need to convert JSON data into Java objects, but how to effectively check and handle the type of attribute values ​​​​is an important skill in this process. This article will answer this question for you and help you better understand and use JSON data conversion technology.

Question content

Suppose I have the following json data. Here I have an id of integer type. The type of id in the java class is string.

{
  "id": 1,
  "name": "user1"
}
@lombok.data
@allargsconstructor
@noargsconstructor
class data {
    string id;
    string name;
}

I want to convert json to the class while strictly checking whether the value of the json attribute is the 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 hope no conversion should happen here, but it will be converted.

Solution

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();
  }
}

Then use this deserializer in the field you want to check:

public class Data {
  @JsonDeserialize(using = CustomDeserializer.class)
  String id;
}

The above is the detailed content of Check the type of Json property value when converted to Java class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete