简体   繁体   English

使用Gson进行JSON反序列化

[英]JSON deserialization with Gson

This is my JSON data: 这是我的JSON数据:

{
  "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() ; 当我使用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. 您需要一个映射JSON数据的类结构。 You don't need to use a Map anywhere, since your JSON does not represent any map! 您不需要在任何地方使用Map ,因为您的JSON不代表任何地图!

In fact it represents an object {...} that contains a field called "boards" , which in turn represents an array [...] of objects {...} ... 事实上,它是一个对象{...}其中包含一个称为字段"boards" ,其又表示一个数组[...]对象的{...} ...

So the class structure that matches your JSON would be something like this (in pseudo-code ): 因此, 您的JSON 匹配的类结构将如下所示(在伪代码中 ):

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: 然后,为了将JSON解析为您的类结构,您只需要执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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