简体   繁体   English

从 JSon 文件中提取数据的空引用

[英]Null Reference On Extracting Data From JSon File

I'm trying to extract data from json file but when I click on a button it gives an exception of NullReference, In fact there is a data in json file but still it gives an exception.我正在尝试从 json 文件中提取数据,但是当我单击一个按钮时,它给出了 NullReference 的异常,实际上 json 文件中有一个数据,但它仍然给出了一个异常。

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

//Json File Ends //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();

            }



    }

Your problem is that you are using DataContractJsonSerializer , and data contract serialization using explicit data contract attributes is opt-in.您的问题是您使用的是DataContractJsonSerializer ,并且使用显式数据协定属性的数据协定序列化是可选的。 What that means is that each member you want to be serialized must be marked with [DataMember] .这意味着您要序列化的每个成员都必须用[DataMember]标记。 From the docs :文档

You can also explicitly create a data contract by using DataContractAttribute and DataMemberAttribute attributes.您还可以使用 DataContractAttribute 和 DataMemberAttribute 特性显式创建数据协定。 This is normally done by applying the DataContractAttribute attribute to the type.这通常通过将 DataContractAttribute 属性应用于类型来完成。 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.然后必须将 DataMemberAttribute 属性应用于数据协定类型的每个成员,以指示它是一个数据成员,即它应该被序列化。

Thus your dt class must look like:因此,您的dt类必须如下所示:

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

You are getting the null reference because dt.Name and dt.Surname , not being serialized, are left null .您正在获取空引用,因为dt.Namedt.Surname未序列化,保留为null

(Incidentally, since those two members are already strings, there is no need to call ToString() on them.) (顺便说一句,由于这两个成员已经是字符串,因此无需对它们调用ToString() 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM