gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:52 25 4
gpt4 key购买 nike

我有一个名为“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 文件,而不是像上面那样将文件转换为字符串然后反序列化?

最佳答案

尝试使用流。

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

关于c# - 如何直接从文件反序列化 json 数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com