如何将 java 对象转换为 Json

How to convert a java object into a Json

我有一个代码,我需要将来自前端的电子邮件(字符串)与存储在我的 ddbb 中的电子邮件(字符串)进行比较。问题是存储的是具有不同字段的电子邮件对象,如验证和创建的那样。 所以我需要检查的只是这个对象的电子邮件等于来自前端的即将到来的电子邮件。

这将是对象:

"addressInformation": {
        "email": "test@it-xpress.eu",
        "verified": true,
        "versource": "n70007"
    }

然后我想将它与字符串 email = "test@it-xpress.eu" 进行比较 也许 Json.stringfy?

干杯!

你有两种方法:

读取到 JsonNode:

new ObjectMapper().readTree("{\"email\": \"test@it-xpress.eu\"}").get("email").asText()

new ObjectMapper().valueToTree(myObject).get("email").asText()

读取特定对象:

class MyObject {
   private String email;
   public String getEmail() { return email; }
}
new ObjectMapper().readValue(MyObject.class).getEmail()

注意!
如果您使用 Spring、Play、Guice 或其他依赖框架,请使用注入现有的 ObjectMapper 或 ObjectMapperBuilder

为牦牛剃毛的众多方法之一。在这种情况下,作为使用 JDK 和 jackson.

的最小可重现示例

jar 文件取自 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
$