Java Android 解析 Json 字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19197015/
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-12 14:58:03  来源:igfitidea点击:

Android parse Json array of Strings

javaandroidarraysjson

提问by Deniz Celebi

How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?

如何在 Android 中解析 Json 字符串数组并将其保存在 java 字符串数组(如:xy[])中?

My Json to be parsed :

我要解析的 Json :

 [
  {
    "streets": [ "street1", "street2", "street3",... ],
  }
 ]

Later in my code I want to populated with that array a spinner item in my layout. Everything i tried enden with only one street item listed in the spinner.

稍后在我的代码中,我想用该数组填充布局中的微调项。我尝试过的所有东西都只在微调器中列出了一个街头项目。

采纳答案by Raghunandan

To parse

解析

try {

   JSONArray jr = new JSONArray("Your json string");
   JSONObject jb = (JSONObject)jr.getJSONObject(0);
   JSONArray st = jb.getJSONArray("streets");
   for(int i=0;i<st.length();i++)
       {
      String street = st.getString(i);
      Log.i("..........",""+street);
      // loop and add it to array or arraylist
        }
}catch(Exception e)
{
        e.printStackTrace();
}

Once you parse and add it to array. Use the same to populate your spinner.

一旦你解析并将其添加到数组中。使用相同的方法填充您的微调器。

[represents json array node

[表示json数组节点

{represents json object node

{代表json对象节点

回答by Hariharan

Try this..

尝试这个..

 JSONArray arr = new JSONArray(json string);

    for(int i = 0; i < arr.length(); i++){

            JSONObject c = arr.getJSONObject(i);        
            JSONArray ar_in = c.getJSONArray("streets");

        for(int j = 0; j < ar_in.length(); j++){    
            Log.v("result--", ar_in.getString(j));
        }
   }

回答by RotatingWheel

We need to make JSON object first. For example,

我们需要先制作 JSON 对象。例如,

JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr  = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length =  " + arr.length());
for(int i=0;i<arr.length();i++)
{...

arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling

arr 可能包含其他 JSON 对象或 JSON 数组。如何转换 JSON 取决于字符串。可以在http://www.hemelix.com/JSONHandling找到一个完整的示例,其中包含有关 JSON 字符串到 JSON 数组的一些解释