[英]How to check json for key and if it exists then set the value in java model Object
[英]Check whether a value exists in a JSON object using Java
我是Java的新手,正嘗試查找並檢查JSON對象中是否存在特定值。 這是我的代碼,
String strUsers = representation.getText();
JSONObject jsonObject = new JSONObject(strUsers);
Iterator<String> keys = jsonObj.keys();
while(keys.hasNext()) {
String key = keys.next();
String val = null;
try {
JSONObject value = jsonObj.getJSONObject(key);
} catch(Exception e) {
}
}
此外,我無法理解如何檢查。 有人可以指導我實現目標嗎?
您應該使用has
的方法。
if(jsonObject.has("your_key")) {
// get the value and do something with it
}
在您的try-catch
塊中,在獲取值之前檢查密鑰是否確實存在。
if (jsonObject.has(key)) {
// then get the value
JSONObject value = jsonObj.getJSONObject(key);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.