如何直接从文件反序列化json数据集?

时间:2015-09-16 04:16:33

标签: c# json json.net

我有一个名为“basic.json”的json文件,其中包含一堆hearthstone卡信息:

mysqldump -u <username> <localdbname> --single-transaction --compress --order-by-primary 
-p<localdbpassword> > mysql -u <rdsusername> --port=3306 --host=<host> -p<rdspassword>

我正在尝试反序列化文件并将卡对象放入字典数据结构中。我设法通过首先将json文件转换为字符串然后反序列化为数据集来实现这一目的:

    {
      "Basic": [

        {
          "cardId": "HERO_09",
          "cardSet": "Basic",
          "collectible": true,
          "faction": "Neutral",
          "health": 30,
          "img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/HERO_09.png",
          "imgGold": "http://wow.zamimg.com/images/hearthstone/cards/enus/animated/HERO_09_premium.gif",
          "locale": "enUS",
          "name": "Anduin Wrynn",
          "playerClass": "Priest",
          "rarity": "Free",
          "type": "Hero"
        },
        {
          "cardId": "HERO_01",
          "cardSet": "Basic",
          "collectible": true,
          "faction": "Neutral",
          "health": 30,
          "img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/HERO_01.png",
          "imgGold": "http://wow.zamimg.com/images/hearthstone/cards/enus/animated/HERO_01_premium.gif",
          "locale": "enUS",
          "name": "Garrosh Hellscream",
          "playerClass": "Warrior",
          "rarity": "Free",
          "type": "Hero"
        }, 
etc.

我的问题是,如何直接从“basic.json”反序列化json文件,而不是将文件转换为字符串,然后像我上面那样进行反序列化?

1 个答案:

答案 0 :(得分:0)

尝试使用流。

using (StreamReader sr = new StreamReader("TestFile.txt"))
{
  JsonSerializer serializer = new JsonSerializer();
  // read the json from a stream
  // json size doesn't matter because only a small piece is read at a time from the HTTP request
  DataSet dataSet = serializer.DeserializeObject<DataSet>(sr )
}

您可以在此处详细了解http://www.newtonsoft.com/json/help/html/Performance.htm