1

I need to parse the following Json

[
    "foo",
    [
        "foot mercato",
        "football",
        "foot center",
        "foorzik",
        "footao"
    ]
]

in java using Gson.

Im really interested in values in the Array: so far I have tried:

String jsonStr = "[" + "\"foo\"," + " [" + "  \"foot mercato\"," + "  \"football\"," + "  \"foot center\"," +
                "  \"foorzik\"," + "  \"footao\"" + " ]" + "]";

JsonParser parser = new JsonParser();
JsonArray array = parser.parse(jsonStr).getAsJsonArray();

any suggestion?

2 Answers 2

1

Once you get your array, you can iterate through all the elements of it.

for(JsonElement e : array) {
    System.out.println(e);
}

which will output

"foo"
["foot mercato","football","foot center","foorzik","footao"]

If you only want the values in the nested array, you can do:

JsonArray nestedArray = parser.parse(jsonStr).getAsJsonArray().get(1).getAsJsonArray();
for(JsonElement e : nestedArray) {
    System.out.println(e);
}

which will output

"foot mercato"
"football"
"foot center"
"foorzik"
"footao"
Sign up to request clarification or add additional context in comments.

Comments

1

This may help:

String jsonStr = "[" + "\"foo\"," + " [" + "  \"foot mercato\"," + "  \"football\"," + "  \"foot center\","
                + "  \"foorzik\"," + "  \"footao\"" + " ]" + "]";

        Gson gson = new Gson();
        ArrayList<Object> dest = new ArrayList<Object>();
        dest = gson.fromJson(jsonStr, dest.getClass());

        for (Object e : dest) {
            System.out.println("T:" + e.getClass().getCanonicalName());
            if (e instanceof String) {
                System.out.println(e);
            } else if (e instanceof ArrayList) {
                for (String ele : (ArrayList<String>) e) {
                    System.out.println(ele);
                }
            }
        }

Will generate:

T:java.lang.String

foo

T:java.util.ArrayList

foot mercato

football

foot center

foorzik

footao

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.