gpt4 book ai didi

c# - 从 JSON 文件中提取数据的空引用

转载 作者:行者123 更新时间:2023-11-30 23:28:23 26 4
gpt4 key购买 nike

我正在尝试从 json 文件中提取数据,但是当我单击一个按钮时,它给出了一个 NullReference 异常,实际上 json 文件中有一个数据,但它仍然给出了一个异常。

//Json File Starts With Name myfile
[
{"Name" : "Stack" , "Surname" : "OverFlow"},
{"Name" : "Google", "Surname" : "INc"}
]

//Json文件结束

 [DataContract]
class dt {
public dt(){}
public string Name { get; set; }
public string Surname { get; set; }
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
StorageFile sf = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\myfile.txt");
var dataString = await FileIO.ReadTextAsync(sf);
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<dt>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(dataString));
List<dt> myData = (List<dt>)json.ReadObject(ms);


foreach (var dt in myData)
{

Windows.UI.Popups.MessageDialog md = new Windows.UI.Popups.MessageDialog(dt.Name.ToString() +" "+ dt.Surname.ToString());
await md.ShowAsync();

}



}

最佳答案

你的问题是你正在使用 DataContractJsonSerializer ,以及使用显式 data contract attributes 的数据契约(Contract)序列化是选择加入。这意味着您要序列化的每个成员都必须标记为 [DataMember] .来自docs :

You can also explicitly create a data contract by using DataContractAttribute and DataMemberAttribute attributes. This is normally done by applying the DataContractAttribute attribute to the type. This attribute can be applied to classes, structures, and enumerations. The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized.

因此您的 dt 类必须如下所示:

[DataContract]
class dt {
public dt(){}
[DataMember]
public string Name { get; set; }
[DataMember]
public string Surname { get; set; }
}

您得到的是空引用,因为 dt.Namedt.Surname 未被序列化,保留为 null

(顺便说一句,因为这两个成员已经是字符串,所以没有必要对它们调用 ToString()。)

关于c# - 从 JSON 文件中提取数据的空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36004845/

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