I have a code where I need to compare an email(string) coming from the frontend to the ones storaged in my ddbb. The thing is that the ones storaged are email objects with differents fields as verified and createdBy let say. So what I need to check is only the email of this object is equal to the upcoming email from the frontend.
This will be the object:
"addressInformation": {
"email": "[email protected]",
"verified": true,
"versource": "n70007"
}
and then I want to compare it with a string email = "[email protected]" Maybe Json.stringfy?
Cheers!
CodePudding user response:
You have a two methods:
Read to JsonNode:
new ObjectMapper().readTree("{\"email\": \"[email protected]\"}").get("email").asText()
new ObjectMapper().valueToTree(myObject).get("email").asText()
Read to specific object:
class MyObject {
private String email;
public String getEmail() { return email; }
}
new ObjectMapper().readValue(MyObject.class).getEmail()
ATTENTION!
If you use Spring, Play, Guice or another dependency framework please use inject existing ObjectMapper or ObjectMapperBuilder
CodePudding user response:
One of many ways to shave the yak. In this case as minimal reproducible example using a JDK and jackson.
The jar files were taken from mvnrepository.
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
class Email {
public String email;
public Boolean verified;
public String versource;
public String toString() { return email " --- " verified " --- " versource;}
}
public class EmailCheck {
static String[] inputJson = {
"{\"email\": \"[email protected]\", \"verified\": true, \"versource\": \"n70007\"}",
"{\"email\": \"[email protected]\", \"verified\": true}",
"{\"email\": \"[email protected]\", \"versource\": \"n70007\"}",
"{\"email\": \"[email protected]\"}",
};
public static void main(String[] args) throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
for (String jsonString : inputJson) {
Email email = objectMapper.readValue(jsonString, Email.class);
System.out.println(email);
}
}
}
$ javac -Xlint -cp jackson-databind-2.13.3.jar:jackson-core-2.13.3.jar:jackson-annotations-2.13.3.jar EmailCheck.java
$ java -cp .:jackson-databind-2.13.3.jar:jackson-core-2.13.3.jar:jackson-annotations-2.13.3.jar EmailCheck
[email protected] --- true --- n70007
[email protected] --- true --- null
[email protected] --- null --- n70007
[email protected] --- null --- null
$