解析没有键的简单JSON数组

Zoo*_*key 4 android json android-json

我需要帮助解析简单的JSONArray,如下所示:

{
 "text":[
  "Morate popuniti polje tekst."
 ]
} 
Run Code Online (Sandbox Code Playgroud)

我试过这个但是我失败了:

 if (response_str != null) {
    try {
        JSONObject jsonObj = new JSONObject(response_str);
        JSONArray arrayJson = jsonObj.getJSONArray("text");

        for (int i = 0; i < arrayJson.length(); i++) {
            JSONObject obj = arrayJson.optJSONObject(i);
            error = obj.getString("text");
        }
    }
Run Code Online (Sandbox Code Playgroud)

dha*_*rms 8

JSONArray是一系列的字符串.你可以这样迭代

JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");

for (int i = 0; i < arrayJson.length(); i++) {
    String error = arrayJson.getString(i);
    // Do something with each error here
}
Run Code Online (Sandbox Code Playgroud)


Rag*_*dan 5

你有JSONArray文字。没有的数组JSONObject

{  // Json object node 
"text":[ // json array text 
 "Morate popuniti polje tekst." // value
]
} 
Run Code Online (Sandbox Code Playgroud)

只需使用

for (int i = 0; i < arrayJson.length(); i++) {
  String value =  arrayJson.get(i);
}
Run Code Online (Sandbox Code Playgroud)

实际上,不需要循环,因为您在json数组中只有1个元素

你可以用

String value = (String) arrayJson.get(0); // index 0 . need to cast it to string
Run Code Online (Sandbox Code Playgroud)

要么

String value = arrayJson.getString(0); // index 0
Run Code Online (Sandbox Code Playgroud)

http://developer.android.com/reference/org/json/JSONArray.html

public Object get (int index)

Added in API level 1
Returns the value at index.

Throws
JSONException   if this array has no value at index, or if that value is the null reference. This method returns normally if the value is JSONObject#NULL.
public boolean getBoolean (int index)
Run Code Online (Sandbox Code Playgroud)

getString

public String getString (int index)

Added in API level 1
Returns the value at index if it exists, coercing it if necessary.

Throws
JSONException   if no such value exists.
Run Code Online (Sandbox Code Playgroud)