简体   繁体   English

通过键获取数组的值

[英]Get value of array by key

I get JSon from url: 我从网址获取JSon:

PHP output: PHP输出:

{"error":"true","code":"inValid"}

Android code : Android代码:

JSONObject jsonRootObject = new JSONObject(result); // result is output php
JSONArray tasks = jsonRootObject.optJSONArray("error");

But not return value of error. 但不会返回错误值。 I want get TRUE value from ERROR key 我想从错误键获得TRUE值

Try this 尝试这个

FYI FYI

In general all the JSON nodes will start with a square bracket or with a curly bracket. 通常,所有JSON节点都将以方括号或大括号开头。 The difference between [ and { is, the square bracket ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject . [{之间的区别是,方括号([)表示JSONArray节点的开始,而大括号({)表示JSONObject So while accessing these nodes we need to call appropriate method to access the data. 因此,在访问这些节点时,我们需要调用适当的方法来访问数据。

JSONObject jsonRootObject = new JSONObject(result);

try 
{
   String strError = jsonRootObject.getString("error");
   String strCode = jsonRootObject.getString("code");

   Log.i("Error",":"+strError);
   Log.i("Code",":"+strCode);
}
catch (JSONException e) 
{
      // TODO Auto-generated catch block
      e.printStackTrace();
}

have you tried getString: 您是否尝试过getString:

JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String mError = jObj.getString("error");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM