5

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

{
 "text":[
  "Morate popuniti polje tekst."
 ]
} 

我已经尝试过了,但我失败了:

 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");
        }
    }
4

3 回答 3

9

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
}
于 2014-04-30T16:27:47.280 回答
7

你有一个JSONArray文本。没有数组JSONObject

{  // Json object node 
"text":[ // json array text 
 "Morate popuniti polje tekst." // value
]
} 

只需使用

for (int i = 0; i < arrayJson.length(); i++) {
  String value =  arrayJson.get(i);
}

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

你可以使用

String value = (String) arrayJson.get(0); // index 0 . need to cast it to string

或者

String value = arrayJson.getString(0); // index 0

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)

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.
于 2014-04-30T16:26:25.113 回答
3

尝试这个:

JSONObject jsonObject = new JSONObject(response_str);
JSONArray arrayJson = jsonObject.getJSONArray("text");
String theString = arrayJson.getString(0);
于 2014-04-30T16:27:38.773 回答