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!!

3
  • Just use jsonschema2pojo.org Commented Nov 14, 2017 at 11:22
  • possible duplicate of stackoverflow.com/questions/39361159/… Commented Nov 14, 2017 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. Commented Nov 14, 2017 at 11:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

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.