-1

Well I'm new to Android. I'm getting a JSON string from a remote URL.

[{"key":"myString1","val":"myValue1"},{"key":"myString2","val":"myValue2"},{"key":"myString3","val":"myValue3"},{"key":"myString4","val":"myValue4"},{"key":"myString5","val":"myValue5"}]

I just need to parse this JSON string & display all key-val pair. I tried something like below from one of the tutorial.

        JSONArray jArray = new JSONArray(str);

        json = jArray.getJSONObject(0); //This will take first pair.

But I don't know the syntax for iterating through whole json object. Any help would be appreciated. Thanks in Advance.

Jenson M John
  • 5,499
  • 5
  • 30
  • 46
  • possible duplicate of [Parsing JSON from URL](http://stackoverflow.com/questions/7467568/parsing-json-from-url) – Confuse Sep 15 '14 at 14:57

1 Answers1

1

There's nothing special in it. You do it like iterating any other array. Let's say you have two String arrays to be filled with values: String[] mKey, mValue

Reading from JSON array will be like:

for (int i = 0; i < array.length(); i++) {
    JSONObject object = array.getJSONObject(i);
    mKey[i] = object.getString("key");
    mValue[i] = object.getString("val");
}
Alexander Zhak
  • 9,140
  • 4
  • 46
  • 72
  • How to assign assign those value to TextView defined already? Can I assign values within loop to TextView ? Sorry, I'm newbie in Android Programming. – Jenson M John Sep 15 '14 at 14:00
  • myTextView.setText(); better set TetView text outside the loop. You can use StringBuilder to generate a string with key-value pairs, then set TextView text. – Alexander Zhak Sep 15 '14 at 14:05