Abdul Manaf
Abdul Manaf

Reputation: 5003

How to parse a two dimensional JSON array in java

This is my json data

 {
    "tag1":["haaai ","hello"],

    "tag2":[["haai1","haai2"],["hello1","hello2","hello3"]]
 }

I can successfully read array tag1 using my java code

 JSONArray msg = (JSONArray) jsonObject.get("tag1");    
 Iterator<String> iterator = msg.iterator();

 while (iterator.hasNext()) {    
        String text = iterator.next();    
        System.out.println(text);
 }

But, I can't read the tag2 array using the above method. Any idea?

Upvotes: 0

Views: 1584

Answers (1)

Codebender
Codebender

Reputation: 14471

You can't read using the same method because the format is different. You will have to use 2 loops instead.

 JSONArray msg = (JSONArray) jsonObject.get("tag2");    
 Iterator<JSONArray> iterator = msg.iterator();

 while (iterator.hasNext()) {
        Iterator<String> innerIterator = iterator.next().iterator();
        while (innerIterator.hasNext()) {
             String text = innerIterator.next();    
             System.out.println(text);
        }
 }

Upvotes: 3

Related Questions