0

I had just started doing android development recently and I have come up with a json that looks like this,

"rows": [

    [ 
        { "val": "abc", 
          "val1":"cde" 
        },

        { "val": "efg", 
          "val1":"hij" 
        },
    ],

    [ 
        { "val": "klm", 
          "val1":"nop" 
        },

        { "val": "qrs", 
          "val1":"tuv" 
        },
    ],
    ........
    ........
    ........
]

Now as you can see the outer array has no keys but the inner ones do. I am using Gson for parsing the json. How should i approach to create a model class for this json? Any help would be appreciated!!

Proloy
  • 343
  • 1
  • 3
  • 14
  • Just use http://www.jsonschema2pojo.org/ – fedepaol Nov 14 '17 at 11:22
  • possible duplicate of https://stackoverflow.com/questions/39361159/parsing-json-object-to-json-array-using-gson – Balasubramanian Nov 14 '17 at 11:23
  • @Balasubramanian Hello, I do not think my question and the question you have pointed out is similar. I have nested arrays but the question you pointed have arrays but they are not nested. – Proloy Nov 14 '17 at 11:35

1 Answers1

0

First of all, this JSON string looks invalid. There shouldn't be a comma after the second element of every two-element inner array. And wrap the whole thing in {} brackets. Like this:

{"rows": [
    [ 
        { "val": "abc", 
          "val1":"cde" 
        },
        { "val": "efg", 
          "val1":"hij" 
        }
    ],
    [ 
        { "val": "klm", 
          "val1":"nop" 
        },
        { "val": "qrs", 
          "val1":"tuv" 
        }
    ]
]}

If you correct those, you can parse it with GSON like this:

    JsonElement root = new JsonParser().parse(jstring);
    root.getAsJsonObject().get("rows")
        .getAsJsonArray().forEach(innerArray -> {
            innerArray.getAsJsonArray().forEach(element -> {
                System.out.println("val equals "+element.getAsJsonObject().get("val"));
                System.out.println("val1 equals "+element.getAsJsonObject().get("val1"));
            });
    });

Obviously, instead of printing you can do whatever you like with those parsed values.

Yaerius
  • 231
  • 2
  • 7