1

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.

3

4 Answers 4

6

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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()]);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.