【问题标题】:How do i deserialize a json dataset directly from a file?如何直接从文件反序列化 json 数据集?
【发布时间】:2015-09-16 04:16:32
【问题描述】:

我有一个名为“basic.json”的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.

我正在尝试反序列化文件并将卡片对象放入字典数据结构中。我已经设法做到了,首先将 json 文件转换为字符串,然后反序列化为数据集:

{

            string json = File.ReadAllText(@"filepath\Basic.json");
            DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
            DataTable dataTable = dataSet.Tables["Basic"];
            Dictionary<CardKey, Card> cards = new Dictionary<CardKey, Card>();


            foreach (DataRow row in dataTable.Rows)
            {

                cards.Add(
                    new CardKey((string)row["cardId"], (string)row["name"]), 
                    new Card((string)row["imgGold"], (string)row["img"]));
            }


        }

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

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    尝试改用流。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-14
      • 2018-10-24
      • 2013-08-17
      • 2023-03-31
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多