简体   繁体   中英

System.ArgumentNullException for Xamarin.Forms using StreamReader

In public ScenarioPage() of ScenarioPage.cs I have the following code to read from a json file:

var assembly = typeof(ScenarioPage).GetTypeInfo().Assembly; 
Stream stream = assembly.GetManifestResourceStream("firstSession.json");

using (StreamReader reader = new StreamReader(stream)) // System.ArgumentNullException
      {
          var json = reader.ReadToEnd();
          List<SessionModel> data = JsonConvert.DeserializeObject<List<SessionModel>>(json); 
          foreach(SessionModel scenario in data)
           {
                    
              label.Text = scenario.title;
              break;
           };

       }

I am getting an ArgumentNullException for the stream input. firstSession.json is in the same folder as ScenarioPage.cs , and it is set as an embedded resource. It seems like Visual Studio is not recognizing that my json file is there. Is this is a bug? Or is there something wrong with my code?

Where did you put the Json File, I put it in the Json File in the root Of PCL like following screenshot. 在此处输入图像描述

Then use following code to read the Json File.

  void GetJsonData()
        {
            string jsonFileName = "firstSession.json";
            ContactList ObjContactList = new ContactList();
            var assembly = typeof(MainPage).GetTypeInfo().Assembly;
            Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
            using (var reader = new System.IO.StreamReader(stream))
            {
                var jsonString = reader.ReadToEnd();

                //Converting JSON Array Objects into generic list    
                ObjContactList = JsonConvert.DeserializeObject<ContactList>(jsonString);
            }
          
            EmployeeView.ItemsSource = ObjContactList.contacts;
           
        }

And here is running GIF.

在此处输入图像描述

I update my demo to you. you can test it https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/PlayMusicInBack.zip

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