1

I have a String like this:

[["123","Albert","foo"],["456","Mark","bar"],["789","Jackson","baz"]]

How can I do to turn it into a corresponding array?

I get this response from a HttpPost in Java (Android).

Thanks in advance

5
  • 3
    Looks like json, use a json parser. Commented Feb 22, 2014 at 4:56
  • might want to specify if u want one array of 9, or 3 arrays of 3 Commented Feb 22, 2014 at 4:57
  • @Sotirios Delimanolis: I got an error: Array cannot be converted in JSONObject user3126670: An array as is shown in chain To list them with loops 123 Albert foo Mark 456 bar 789 Jackson baz Commented Feb 22, 2014 at 4:59
  • The error is pretty descriptive. You're trying to get a json object from a json array. That doesn't make sense. Get a json array instead. Commented Feb 22, 2014 at 5:03
  • Suppose that in the table of the database, the columns are: id, name, nick try { String s = ""; JSONArray jArray = new JSONArray(result); for (int i=0;i<jArray.length();i++) { JSONObject json = jArray.getJSONObject(i); s = s + "Id: " + json.getString("id")+"\n"+ "Name: " + json.getString("name")+"\n"+ "Nick: " + json.getString("nick")+"\n\n"; } resultView.setText(s); } catch(Exception e) { Log.e("Log", "Error parsing JSON :("+e.toString()); } Commented Feb 22, 2014 at 5:06

3 Answers 3

3

Try this.

JSONArray new_array = new JSONArray(string);
for(int i =0; i < new_array.length(); i++){
     JSONArray arr = new_array.getJSONArray(i);
     for(int j =0; j < arr.length(); j++){
          Log.v("result--",""+arr.getString(j));
     }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to make it a regular two-dimensional array? Because I need to manipulate the indices Or with JSON I can manipulate indexes? To display something like: s=s + "Id :"+arr[0]+"\n"+ "Name :"+arr[1]+"\n"+ "Nick :"+arr[2]+"\n\n";
Done! not arr[index] Is arr.get(index) :D
3

Use GSON like:

Gson gson = new Gson();
String[][] myTypes = gson.fromJson(str, String[][].class);

search for more example of how to use GSON library.

Comments

2

In your format you have to fetch your data for JSONArray instead of JSONObject.

So you have to use this which make sense

    JSONArray jArray = new JSONArray(yourResponsestr);
    for(int i =0; i < jArray .length(); i++){
    JSONArray arr = myarray.getJSONArray(i);
    for(int j =0; j < myarray.length(); j++){
      Log.v("Response Array -->",""+arr.getString(j));
    }
    }

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.