-3

我的网络服务有这个数组: {"update":true,"msg":"Logged in Bro","role":"admin"}

现在,我需要在 Android 中使用它来处理我的应用程序,而不是登录。所以我在这里需要一种将这些数据格式化为名称值对或单个变量的方法,以便我可以使用它们。

我目前正在使用它,但它会强制关闭我的应用程序:

try {

            JSONObject jsonRootObject = new JSONObject(result);

            //Get the instance of JSONArray that contains JSONObjects
            JSONArray jsonArray = jsonRootObject.optJSONArray("");

            //Iterate the jsonArray and print the info of JSONObjects
            for(int i=0; i < jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                update = jsonObject.optString(jsonObject.optString("update").toString());
                message = jsonObject.optString("msg").toString();
                role = jsonObject.optString(jsonObject.optString("role").toString());


            }

        } catch (JSONException e) {e.printStackTrace();}
4

2 回答 2

1

我假设result包含您的 JSON 作为String

{"update":true,"msg":"Logged in Bro","role":"admin"}

所以,

JSONObject jsonRootObject = new JSONObject(result);

创建一个具有三个属性的 JSON 对象updatemsgrole。您可以像这样访问它们:

boolean update = jsonRootObject.optBoolean("update");
String msg = jsonRootObject.optString("msg");
String role = jsonObject.optString("role");

您的代码崩溃是jsonArray.length()因为jsonArray == null:jsonRootObject.optJSONArray("");返回,因为您的对象null中没有包含键的数组。""


optString("msg").toString();

本身就是不合逻辑的。optString要么返回 aString要么nullmsg如果该属性不存在,您的代码将崩溃。如果您希望存在属性,请使用getString而不是optString. 一般来说,不要调用toString()s String


jsonObject.optString(jsonObject.optString("role").toString());

也没有意义。您的对象中没有与 property 的值相等的键role

于 2015-07-15T16:39:05.190 回答
1

要解析您提供的 JSON,您需要以下内容:

   JSONObject jsonObject = new JSONObject(jsonString);

   update = jsonObject.optBoolean("update");
   message = jsonObject.optString("msg");
   role = jsonObject.optString("role");
于 2015-07-15T16:33:44.710 回答