大家好,我想我的问题已经解决了,但是还没有完全解决。我认为问题与我的JSON文件周围有括号有关,我需要删除它们吗?
这是JSON文件中的内容:
[{"EMPLID":"102104","NAME":"t,g"},{"EMPLID":"108160","NAME":"m,t"},{"EMPLID":"127186","NAME":"t,m"}]
我有两种形式,一种是从oracle表中提取数据并将其序列化为文件,另一种是应该对其进行反序列化然后填充数据集。
选择数据并将其放入数据表后,我将使用以下内容进行序列化:
using (StreamWriter file = File.CreateText(@"C:\Users\user\Desktop\assign.json"))
{
JsonSerializer serializer = new JsonSerializer();
//serialize object directly into file stream
serializer.Serialize(file, dt);
}
然后关闭我的表单,并使用以下命令对文件进行反序列化
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Form frm2 = new Form2();
Form frm3 = new Form3();
if (this.Visible == false)
{
this.Hide();
MessageBox.Show("closing");
this.Show();
//AssgnData movie1 = JsonConvert.DeserializeObject<AssgnData>(File.ReadAllText(@"C:\Users\user\Desktop\assign.json"));
using (StreamReader file = File.OpenText(@"C:\Users\user\Desktop\assign.json"))
{
JsonSerializer serializer = new JsonSerializer();
AssgnData movie2 = (AssgnData)serializer.Deserialize(file, typeof(AssgnData));
}
}
}
public class AssgnData
{
public string EMPLID { get; set; }
public string NAME { get; set; }
}
}
答案 0 :(得分:0)
您的json与AssgnData
的集合匹配,而不是单个项目。因此,您应该将其反序列化为IEnumerable<AssgnData>
:
using (StreamReader file = File.OpenText(@"C:\Users\user\Desktop\assign.json"))
{
JsonSerializer serializer = new JsonSerializer();
IEnumerable<AssgnData> movie2 = (IEnumerable<AssgnData>)serializer.Deserialize(file, typeof(IEnumerable<AssgnData>));
}
如果使用Newtonsoft.Json
,它看起来像:
string json = "[{\"EMPLID\":\"102104\",\"NAME\":\"t,g\"},{\"EMPLID\":\"108160\",\"NAME\":\"m,t\"},{\"EMPLID\":\"127186\",\"NAME\":\"t,m\"}]";
var result = JsonConvert.DeserializeObject<IEnumerable<AssgnData>>(json);