Home > Java > body text

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

WBOY
Release: 2024-02-22 14:16:06
forward
487 people have browsed it

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"
}
Copy after login
@lombok.data
@allargsconstructor
@noargsconstructor
class data {
    string id;
    string name;
}
Copy after login

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);
Copy after login

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

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

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!