Matthew Pans
Matthew Pans

Reputation: 783

Xamarin forms: How to parse local JSON data file stored in the project?

I have a local JSON file. I need to parse data from that file and need a list with date,color and message details.

Data format in JSON file:

{"01-01-2017":{"color":"white","message":"The Octave Day of Christmas Solemnity of the Blessed Virgin Mary, the Mother of God Lectionary: 18"},"02-01-2017":{"color":"white","message":"Memorial of Saints Basil the Great and Gregory Nazianzen, Bishops and Doctors of the Church Lectionary: 205",.......}}

Model Class

public class JsonContent
{
    public string date { get; set; }
    public string color { get; set; }
    public string message { get; set; }
}

I tried the below code:

string jsonString;
string jsonFileName = "Files.prayers.json";
var assembly = typeof(HomePage1).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
using (var reader = new System.IO.StreamReader(stream))
{
     jsonString = reader.ReadToEnd();
}
List <JsonContent> newList = new List<JsonContent>();
//I need to add all the items into the above list

How can I get the list with date,color and message details? After this I need to show the dates with color on a XamForms.Enhanced.Calendar. I know how to show special dates in calendar, but stuck on this data parsing.

Upvotes: 0

Views: 107

Answers (1)

Jason
Jason

Reputation: 89102

docs

I'd try something like this

Dictionary<string, JsonContent> jsonData = JsonConvert.DeserializeObject<Dictionary<string, JsonContent>>(jsonString);
foreach (var item in jsonData)
{
    Debug.WriteLine("Date:>>" + item.Key);
    Debug.WriteLine("color:>>" + item.Value.color);
    Debug.WriteLine("message:>>" + item.Value.message);
}

Upvotes: 2

Related Questions