response: [ { id: 1, first_name: 'Павел', last_name: 'Дуров', sex: 2, photo_id: '1_288668576', can_write_private_message: 0 }, { id: 2, first_name: 'Александра', last_name: 'Владимирова', sex: 1, photo_id: '2_332227351', can_write_private_message: 0 }, { id: 3, first_name: 'DELETED', last_name: '', deactivated: 'deleted', sex: 0, can_write_private_message: 0 } ] 

How in Java to get ID from all elements? I'm using the com.google.gson library.

    1 answer 1

    Way for the lazy

    Received object model - and forward.

     JsonArray a = new JsonParser().parse(json).getAsJsonArray(); for (int i = 0; i < a.size(); i++) { int id = a.get(0).getAsJsonObject().get("id").getAsInt(); } 

    Long way

    We describe classes ...

     class Human { string id; // ... } 

    ... and we have a glamorous massive

     Human[] humans = new Gson().fromJson(json, Human[].class); 

    The right way

    Find a ready-made wrapper over the API and do not suffer. Everything is invented before you.

    • Well, I did not find a suitable API for my "projects", and decided to make my own, I used it for more than a month, and now I came across an array that I see first. Thanks for the code! c: - Mikhail Ivanov
    • java.lang.IllegalStateException: This is not a JSON Array. with my code it was the same - Mikhail Ivanov
    • @ MikhailIvanov You didn’t have braces around the response: [ ] , about which you forgot to mention? Then start with ...getAsJsonObject().get("response") . - Athari
    • no, no, I put the whole json in the question - Mikhail Ivanov
    • @ MikhailIvanov The text you give is not valid JSON. From the outside, there must be either { ... } or [ ... ] (plus there may be a bare primitive). { response: [ { id: ... } ... ] } is correct, [ { id: ... } ... ] is correct, response: [ { id: ... } ... ] is incorrect . You are definitely missing something. - Athari