简体   繁体   中英

Converting a String to Json Object with validation in java

I am having a string like ,

name = " {
        "Name" : "MyName"
      }"

and having a Model class like ,

 @Valid
    Class Model {
        @JsonProperty("Name")
        @Size(min = 1)
        @NotNull
        private String name;
    }

Now I am converting the string to Java Object by following code,

   Model name = objectMapper.readValue(name, Model.class);

So the validation(min = 1 and not null) is not happening with this. How can I validate when I am converting a string to java object?

i will try to help u.

I have an idea and it´s that u divide the process in 2 parts:

First, u take the json and put in on a JSONObject:

import org.json.JSONObject;
...
JSONObject json= new JSONObject(name);

Then, u can call, for example, a function passing a json that validate the values of json an if is correct return a model object:

public Model functionExample(JSONObject json){
     try{
          if(json.has("Name") && json.getString("Name")!=null){    
               return new Model(json.getString("Name"));         
          }
     }catch(Exception ex){
          return new Model();
     }
}

This check if the field "Name" exists and it´s not null.

I don´t know if it is what u want.

I hope it help u.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM