简体   繁体   中英

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 File Starts With Name myfile
[
{"Name" : "Stack" , "Surname" : "OverFlow"},
{"Name" : "Google", "Surname" : "INc"}
]

//Json File Ends

 [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. What that means is that each member you want to be serialized must be marked with [DataMember] . From the 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.

Thus your dt class must look like:

[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 .

(Incidentally, since those two members are already strings, there is no need to call ToString() on them.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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