A while back, I wrote around 200 JSON objects out to provide a data source for a web app that I was writing that would allow the user to track the mountains that they had climbed. The app was really more of a practise thing than anything else and I sort of forgot about it. Until, one day I thought that this would be a good idea for a mobile app. I already had all the data, so it would be easy to consume in a Xamarin app, right?

Well, the answer is that yes, it is, but it is slightly different to how it’s done in an ASP.NET or other C# app.

Here’s how you would do it in ASP.NET or a simple Console app. Let’s say we have created a C# object called Mountain to model the data. I have my json in a local file and for ease of demonstration in the same folder as my main class, which is calling the following:


public List<Mountain> Data { get; set; }
  
private IList<Mountain> GetMainData()
{
          List<Mountain> myList = new List<Mountain>();
          string kJson = File.ReadAllText(path: "data.json");
          return Data = JsonConvert.DeserializeObject<List<MountainData>>(kJson);
}
	

So far, so good. I now have a C# list of all my json objects and can do whatever I like with them now.

Unfortunately not in Xamarin…

That wasn’t working for me in an app, though. After a fair bit of tweaking, I came up with a solution to do what the ASP.NET code did:

public List<Mountain> Data { get; set; }

private IList<Mountain> GetMainData()
{
         var assembly = this.GetType().GetTypeInfo().Assembly;
         Stream stream = 
                assembly.GetManifestResourceStream("data.json"); // make sure you inset the full 
                                                                 // namespace here, not just the 
                                                                 // name of the file
         using (var reader = new StreamReader(stream))
         {
             var kJson = reader.ReadToEnd();
             return Data = JsonConvert.DeserializeObject<List<Mountain>>(kJson);
         }
 }

This worked, so then I could get on to grouping and filtering the data. Hope that helps someone.

Cheers, John.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *