Parsing string array from JSON object

2019-09-24 16:22发布

It might be too easy but I just cannot find a solution to this. How can I directly parse the string array out of the JSON object?

For example,

json = {"names":["John", "Alex", "David"]}

I cannot do json.getJSONArray("names") since it doesn't return a string array.

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-24 16:37

Try this buddy, you will get the result in an array of strings.

    String json = "{\"names\":[\"John\", \"Alex\", \"David\"]}";
    JSONObject jsonObject = new JSONObject(json);
    JSONArray jsonArray = jsonObject.getJSONArray("names");
    List<String> list = new ArrayList<String>();
    for (int i = 0; i < jsonArray.length(); i++) {
        list.add(jsonArray.getString(i));
    }
    String[] stringArray = list.toArray(new String[list.size()]);
查看更多
Luminary・发光体
3楼-- · 2019-09-24 16:38

You can try this my friend

try 
{

  JSONObject jsonObj = new JSONObject("Your json string");
  JSONArray jsonArray = jsonObj .getJSONArray("names");

   for(int i=0;i<jsonArray .length();i++)
   {
      String name= jsonArray.getString(i);
      Log.i("..........",""+name);
      // loop and add it to array or arraylist
   }
}catch(Exception e)
{
        e.printStackTrace();
}
查看更多
再贱就再见
4楼-- · 2019-09-24 16:47

Try this function

public void ParseJsonArray(json){
try {
//if you have 1 column in json array
        JSONArray jsonArray = json.getJSONArray("names"); 
        int count = 0;

//if you have more columns      
        while (count<jsonArray.length()){

            JSONObject JO = jsonArray.getJSONObject(count);
            String s1 = JO.getString("column1");
            String s2 = JO.getString("column2");
            String s3 = JO.getString("column3");           
            count++;        }``

    String StrFinal = jsonArray;

    } catch (JSONException e) {
        e.printStackTrace();  }
    }
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-09-24 16:57

You can get the data as a json array and the loop through it to create a list

JSONObject jsonObject = new JSONObject("{names:['1','2','3']}");
JSONArray jsonArray = jsonObject.getJSONArray("names");

List<String> names = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++){
     names.add(jsonArray.getString(i));
}
System.out.println(names);
查看更多
登录 后发表回答