How to convert a java object into a Json

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": "test@it-xpress.eu",
        "verified": true,
        "versource": "n70007"
    }

and then I want to compare it with a string email = "test@it-xpress.eu"
Maybe Json.stringfy?

Cheers!

>Solution :

You have a two methods:

Read to JsonNode:

new ObjectMapper().readTree("{\"email\": \"test@it-xpress.eu\"}").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

Leave a Reply