[英]Data from the JSON array in Java
我有这个 JSON 数据,经过长时间的工作,我找不到获得结果的方法。 我的目标是获取video_url的值,即使它是 null 但是是的,我已经进行了检查以检查是否有内容。 我已经尝试了所有可能的方法,但我得到的只是没有 output。
这是我的代码:
{
"data":
[
{
"type":"project-users",
"id":"1",
"attributes":
{
"video-url":null
},
"links":
{
"self": "http://localhost:3000/api/project-users/1"
}
},
{
"type":"project-users",
"id":"2",
"attributes":
{
"video-url":null
},
"links":
{
"self":"http://localhost:3000/api/project-users/2"
}
},
{
"type":"project-users",
"id":"3",
"attributes":
{
"video-url":null
},
"links":
{"self":"http://localhost:3000/api/project-users/3"
}
}
] }
为了从属性 object 中获取 video_url 的值,我这样做了但失败了:
private void jSONLoadData(String response) throws JSONException{
//talk about this in getting the video url
JSONObject obj = new JSONObject(response);
JSONArray jArray = obj.getJSONArray("data");
for(int i=0; i<jArray.length() ; i++){
JSONObject jsonObj = jArray.getJSONObject(i);
String url = jsonObj.getJSONObject("attributes").getString("video_url");
Log.e("URL", url);
if(url.equals(null) || url.equals("")){
Toast.makeText(getApplicationContext(), "Empty", Toast.LENGTH_SHORT)
.show();
}
}
}
注意:response 就是上面的 JSON 数据。
我认为与其调用getString("video_url");
首先检查video_url
是否为 null(即isNull("video_url")
)。
请尝试使用以下代码。
private void jSONLoadData(String response) throws JSONException{
//talk about this in getting the video url
JSONObject obj = new JSONObject(response);
JSONArray jArray = obj.getJSONArray("data");
for(int i=0; i<jArray.length() ; i++){
JSONObject jsonObj = jArray.getJSONObject(i);
boolean isURLNull = jsonObj.getJSONObject("attributes").isNull("video_url");
String url="";
if(!isURLNull){
url = jsonObj.getJSONObject("attributes").getString("video_url");
}
if(isURLNull || url.equals("")){
Toast.makeText(getApplicationContext(), "Empty", Toast.LENGTH_SHORT)
.show();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.