简体   繁体   中英

JSON deserialization with Gson

This is my JSON data:

{
  "boards": [
    {
        "board": "3",
        "title": "3DCG",
        "ws_board": 1,
        "per_page": 15,
        "pages": 11
    },
    {
        "board": "a",
        "title": "Anime & Manga",
        "ws_board": 1,
        "per_page": 15,
        "pages": 11
    },
    {
        "board": "adv",
        "title": "Advice",
        "ws_board": 1,
        "per_page": 15,
        "pages": 11
    },
    ...
  ]
}

This is my code for deserialization:

JSONObject json = readJsonFromUrl("http://api.4chan.org/boards.json");
String jsonBoards = json.toString();
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(jsonBoards, map.getClass());

But it doesn't get the job done. I need a way to get the boards name, title, and all the that information for each board. When I use map.get() ; the key is "boards" but I want a map of every board and title and so on.

You need a class structure that maps your JSON data. You don't need to use a Map anywhere, since your JSON does not represent any map!

In fact it represents an object {...} that contains a field called "boards" , which in turn represents an array [...] of objects {...} ...

So the class structure that matches your JSON would be something like this (in pseudo-code ):

class Response
  List<Board> boards

class Board
  String board
  String title
  int ws_board
  int per_page
  int pages

Then, in order to parse the JSON into your class structure, you just need to do this:

Gson gson = new Gson();
Response response = gson.fromJson(jsonBoards, Response.class);

So you'll have all the data of all your boards into:

String nameI = response.getBoards().get(i).getName();
String titleI = response.getBoards().get(i).getTitle();
//and so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM