[英]How to convert a java object into a Json
我有一个代码,我需要将来自前端的电子邮件(字符串)与存储在我的 ddbb 中的电子邮件(字符串)进行比较。 问题是存储的是电子邮件对象,它们具有经过验证和创建的不同字段。 所以我需要检查的是只有这个对象的电子邮件等于来自前端的即将到来的电子邮件。
这将是对象:
"addressInformation": {
"email": "test@it-xpress.eu",
"verified": true,
"versource": "n70007"
}
然后我想将它与字符串电子邮件进行比较 =“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
$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.