我有一个json文件名为"basic "。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(@"filepathBasic.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"]));
}
}
我的问题是,我如何从"基本"直接反序列化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