문제

I'm just starting off with json parsing and writing, and am using gson to do so. Let's say I want to access something towards the bottom of the file, do you have to iterate through each line in the json file to get to that line?

How do you jump to Alice without having to iterate through everything Bob has? Right now I only know how to use beginObject(), beginArray() to open Bob, go through them, then close Bob, then reach Alice. e.g.

{
"Bob": {
    "following": [
        215876567,
        64044676,
        276716878,
        208675951,
        151503222,
        ],
    "followers": [
                    720567433,
        1005407395,
        2432297370,
        2463742694,
        2463741222,
        51101660,
        2463700218,
        2463741192,
        405107240,
            ]
        },
"Alice": {
   "location": "New York"
        }
}
도움이 되었습니까?

해결책

You can get direct Alice as below

JsonParserjsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(YOUR_JSON_STRING_HERE);

// get JsonElement for Alice as like this

JsonElement aliceJsonElement = jsonElement.getAsJsonObject().get("Alice");

It will give you this json object {"location":"New York"}

Finally you can parse it as

Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(aliceJsonElement, mapType);

// iterate map

Like this you can get Bob AND following

jsonElement.getAsJsonObject().get("Bob")
jsonElement.getAsJsonObject().get("Bob").getAsJsonObject().get("following")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top