C# 当我知道JSON文件中有什么内容时,如何从JSON文件反序列化字典?

C# 当我知道JSON文件中有什么内容时,如何从JSON文件反序列化字典?,c#,C#,我试图将字典写入一个.json文件,然后从这个文件中读取它。我成功地将它序列化并写入文件,但我不知道当我试图读取它时我做错了什么。Visual Studio写入以下错误: 无法将类型“object”隐式转换为 “System.Collections.Generic.Dictionary”是一个显式 转换存在(是否缺少演员阵容?) 我尝试了以下方法: Dictionary<string, object> last_record = new Dictionary<string, o

我试图将字典写入一个.json文件,然后从这个文件中读取它。我成功地将它序列化并写入文件,但我不知道当我试图读取它时我做错了什么。Visual Studio写入以下错误:

无法将类型“object”隐式转换为 “System.Collections.Generic.Dictionary”是一个显式 转换存在(是否缺少演员阵容?)

我尝试了以下方法:

Dictionary<string, object> last_record = new Dictionary<string, object>();
不要帮忙

以下是我使用的代码:

using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;

Dictionary<string, object> my_database = new Dictionary<string, object>();
Dictionary<string, string> my_record = new Dictionary<string, string>();

my_record.Add("Name", "John");
my_record.Add("Surname", "Smith");
my_record.Add("Country", "UK");

my_database.Add("ID", "01");
my_database.Add("Person", my_record);

string json = JsonConvert.SerializeObject(my_database);
StreamWriter sw = new StreamWriter("D:\\Test.json", true, Encoding.ASCII);
sw.WriteLine(json);
sw.Close();

//
// In another part of the program:
//
string last_line;
last_line = File.ReadLines("D:\\Test.json").Last();

// next line produces the error:    
Dictionary<string, object> last_record = JsonConvert.DeserializeObject(last_line);
last_ID = last_record["ID"].ToString();
使用系统;
使用System.IO;
使用System.Collections.Generic;
使用Newtonsoft.Json;
使用System.Linq;
Dictionary my_database=新字典();
Dictionary my_record=新字典();
我的记录。添加(“姓名”、“约翰”);
我的记录。加上(“姓氏”、“史密斯”);
我的记录。添加(“国家”、“英国”);
my_数据库。添加(“ID”,“01”);
我的_数据库。添加(“Person”,我的_记录);
string json=JsonConvert.SerializeObject(my_数据库);
StreamWriter sw=新的StreamWriter(“D:\\Test.json”,true,Encoding.ASCII);
sw.WriteLine(json);
sw.Close();
//
//在该计划的另一部分:
//
字符串最后一行;
last_line=File.ReadLines(“D:\\Test.json”).last();
//下一行生成错误:
Dictionary last_record=JsonConvert.DeserializeObject(最后一行);
last_ID=last_记录[“ID”]。ToString();

为了从转换器中获取通用变量,您可以使用:

var last_record = JsonConvert.DeserializeObject<Dictionary<string,object>>(last_line);
var last\u record=JsonConvert.DeserializeObject(最后一行);

否则,您将得到返回
对象的非泛型版本

是的,这是显而易见的。非常感谢。
var last_record = JsonConvert.DeserializeObject<Dictionary<string,object>>(last_line);