我有一個代碼,我需要將來自前端的電子郵件(字串)與存盤在我的 ddbb 中的電子郵件(字串)進行比較。問題是存盤的是電子郵件物件,它們具有經過驗證和創建的不同欄位。所以我需要檢查的是只有這個物件的電子郵件等于來自前端的即將到來的電子郵件。
這將是物件:
"addressInformation": {
"email": "[email protected]",
"verified": true,
"versource": "n70007"
}
然后我想將它與字串電子郵件進行比較 =“[email protected]”也許是 Json.stringfy?
干杯!
uj5u.com熱心網友回復:
你有兩種方法:
讀取 JsonNode:
new ObjectMapper().readTree("{\"email\": \"[email protected]\"}").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
uj5u.com熱心網友回復:
給牦牛剃毛的許多方法之一。在這種情況下,作為使用 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\": \"[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
$
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/483573.html
