Android 解析没有键的简单 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23393312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:05:50  来源:igfitidea点击:

Parse simple JSON Array without key

androidjsonandroid-json

提问by Zookey

I need help with parsing simple JSONArray like this:

我需要帮助解析这样的简单 JSONArray:

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

I have tried with this but I failed:

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

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

回答by dharms

Your JSONArrayis an array of Strings. You can iterate this way

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
}

回答by Raghunandan

You have a JSONArraytext. There is no array of JSONObject.

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

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

Just use

只需使用

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

In fact there is no need for a loop as you have only 1 element in json array

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

You can just use

你可以使用

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

Or

或者

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

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

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

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.

回答by matiash

Try this:

尝试这个:

JSONObject jsonObject = new JSONObject(response_str);
JSONArray arrayJson = jsonObject.getJSONArray("text");
String theString = arrayJson.getString(0);