简体   繁体   中英

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!

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

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\": \"test@it-xpress.eu\", \"verified\": true, \"versource\": \"n70007\"}",
        "{\"email\": \"test@it-xpress.eu\", \"verified\": true}",
        "{\"email\": \"test@it-xpress.eu\", \"versource\": \"n70007\"}",
        "{\"email\": \"test@it-xpress.eu\"}",
    };
    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           
test@it-xpress.eu --- true --- n70007
test@it-xpress.eu --- true --- null
test@it-xpress.eu --- null --- n70007
test@it-xpress.eu --- null --- null
$ 

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