android how to convert json array to string array

后端 未结 5 1672
时光取名叫无心
时光取名叫无心 2020-12-09 21:22

I have an app where I fetch data from server(json) in the form of array & by using the index i used in my app, like below.

JSONObject topobj = new JSONOb         


        
相关标签:
5条回答
  • 2020-12-09 21:36

    This I think is what you searching for

    ArrayList<String> list = new ArrayList<String>();     
    JSONArray jsonArray = (JSONArray)jsonObject; 
    if (jsonArray != null) { 
       for (int i=0;i<jsonArray.length();i++){ 
        list.add(jsonArray.get(i).toString()); 
    } 
    
    0 讨论(0)
  • 2020-12-09 21:44

    I just did this yesterday! If you're willing to use a 3rd party library then you can use Google GSON, with the additional benefit of having more concise code.

    String json = jsonArray.toString();
    Type collectionType = new TypeToken<Collection<String>>(){}.getType();
    Collection<String> strings = gson.fromJson(json, collectionType);
    
    for (String element : strings)
    {
        Log.d("TAG", "I'm doing stuff with: " + element);
    }
    

    You can find more examples in the user guide.

    0 讨论(0)
  • 2020-12-09 21:53

    This should help you.

    Edit:

    Maybe this is what you need:

    ArrayList<String> stringArray = new ArrayList<String>();
    JSONArray jsonArray = new JSONArray();
    for(int i = 0, count = jsonArray.length(); i< count; i++)
    {
        try {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            stringArray.add(jsonObject.toString());
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 22:01

    Another elegant kotlin way:

    val list = jsonArray.map { jsonElement -> jsonElement.toString() }
    

    And just convert to array if needed

    0 讨论(0)
  • 2020-12-09 22:02

    Assume that you already have JSONArray jsonArray:

    String[] stringArray = new stringArray[jsonArray.length()];
    for(int i = 0, count = jsonArray.length(); i< count; i++)
    {
        try {
            String jsonString = jsonArray.getString(i);
            stringArray[i] = jsonString.toString();
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
提交回复
热议问题