我從一個我無法控制的 api 得到這個深度嵌套的 JSON 回應,
獲取“generalDetails”然后在安全、地址、帳戶和移動設備下找到第一個真實值的最佳方法應該是什么?
{
"info_code": "201",
"info_description": "info description",
"data": {
"status": "here goes the status",
"failure_data": {
"source": "anySource",
"details": {
"data": {
"server_response": {
"generalDetails": {
"security": {
"isAccountLocked": "false"
},
"address": {
"isAddresExists": "true"
},
"account": {
"accountExists": "true",
"isValidAccount": "true"
},
"mobile": {
"mobileExists": "true"
}
}
}
}
}
}
}
}
我的請求如下所示:
@Autowired
private WebClient.Builder webClientBuilder;
String resp = webClientBuilder.build().get().uri(URL)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class).block();
uj5u.com熱心網友回復:
首先,構建模型,這里自動https://codebeautify.org/json-to-java-converter。
然后用模型讀取資料
.bodyToMono(MyData.class)
然后決定如何評估需求find the first true value under security, address, account and mobile。
“第一”是什么意思?JSON 沒有明確指示的自然順序(例如欄位“order”:2)。
注意回應的“true”、“false”是字串,而不是布林值。
一旦您擁有包含資料的模型,您可以執行以下操作:
Object firstTrue(GeneralDetails gd) {
// No null checks here
if ("true".equals(gd.getSecurtity().isLockedAccount())) return gd.getSecurtity();
if ("true".equals(gd.getAddress().isAddressExists())) return gd.getAddress();
if ("true".equals(gd.getAccount().isAccountExists()) || "true".equals(gd.getAccount().isAccountValid())) return gd.getAccount();
if ("true".equals(gd.getMobile().isMobileExists())) return gd.getMobile();
return null;
}
uj5u.com熱心網友回復:
https://github.com/octomix/josson
反序列化
Josson josson = Josson.fromJsonString(
"{"
" \"info_code\": \"201\","
" \"info_description\": \"info description\","
" \"data\": {"
" \"status\": \"here goes the status\","
" \"failure_data\": {"
" \"source\": \"anySource\","
" \"details\": {"
" \"data\": {"
" \"server_response\": {"
" \"generalDetails\": {"
" \"security\": {"
" \"isAccountLocked\": \"false\""
" },"
" \"address\": {"
" \"isAddresExists\": \"true\""
" },"
" \"account\": {"
" \"accountExists\": \"true\","
" \"isValidAccount\": \"true\""
" },"
" \"mobile\": {"
" \"mobileExists\": \"true\""
" }"
" }"
" }"
" }"
" }"
" }"
" }"
"}");
詢問
JsonNode node = josson.getNode(
"data.failure_data.details.data.server_response"
".generalDetails.**.mergeObjects().assort().[*]");
System.out.println(node.toPrettyString());
輸出
{
"isAddresExists" : "true"
}
如果改變isAddresExists并accountExistsfalse
" \"generalDetails\": {"
" \"security\": {"
" \"isAccountLocked\": \"false\""
" },"
" \"address\": {"
" \"isAddresExists\": \"false\""
" },"
" \"account\": {"
" \"accountExists\": \"false\","
" \"isValidAccount\": \"true\""
" },"
" \"mobile\": {"
" \"mobileExists\": \"true\""
" }"
" }"
輸出
{
"isValidAccount" : "true"
}
如果您只想要鍵名
String firstTureKey = josson.getString(
"data.failure_data.details.data.server_response"
".generalDetails.**.mergeObjects().assort().[*].keys().[0]");
System.out.println(firstTureKey);
輸出
isValidAccount
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/517221.html
