【问题标题】:Xamarin Forms: How to parse data from a local JSON file?Xamarin Forms:如何解析本地 JSON 文件中的数据?
【发布时间】:2019-09-26 18:59:30
【问题描述】:

我有一个本地 JSON 文件。我需要根据日期解析该文件中的数据。

JSON 文件中的数据格式:

{"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"},"03-01-2017":{"color":"white","message":"Christmas Weekday Lectionary: 206"},"04-01-2017":{"color":"white","message":"Memorial of Saint Elizabeth Ann Seton, Religious Lectionary: 207"},"05-01-2017":{"color":"white","message":"Memorial of Saint John Neumann, Bishop Lectionary: 208"},"06-01-2017":{"color":"white","message":"Christmas Weekday Lectionary: 209"},"07-01-2017":{"color":"white","message":"Christmas Weekday Lectionary: 210"},"08-01-2017":{"color":"white","message":"The Epiphany of the Lord Lectionary: 20"},"09-01-2017":{"color":"white","message":"The Baptism of the Lord Lectionary: 21"},"10-01-2017":{"color":"darkseagreen","message":"Tuesday of the First Week in Ordinary Time Lectionary: 306"}}

根据我需要解析相应消息的日期。我该怎么做?

【问题讨论】:

  • 如果您在控制台中打印变量jsonString,您会看到什么?在调用JObject.Parse(jsonString);之前做
  • 我测试了您提供的代码,没有错误,它运行良好。能否提供代码示例供我测试?
  • @pinedax 问题出在我的 JSON 文件上。它包含一些特殊字符。
  • @WendyZang 问题出在我的 JSON 文件上。它包含一些特殊字符。

标签: json parsing xamarin.forms


【解决方案1】:

解决方案:

  1. 向 PCL 项目添加 JSON 文件,并将 Build Action 设置为 Embedded Resource。
  2. 根据日期获取值。

    void GetJsonData(string date)
    {
    try
    {
        string jsonFileName = "prayers.json";
        var assembly = typeof(HomePage).GetTypeInfo().Assembly;
    
        Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
        using (var reader = new System.IO.StreamReader(stream))
        {
            var jsonString = reader.ReadToEnd();
    
            JObject obj = JObject.Parse(jsonString);
    
            var color = obj[date]["color"];
            var message = obj[date]["message"];
        }
    }
    catch(Exception e)
    {
        Debug.WriteLine("PrayerException:>"+e);
    }
    }
    

【讨论】:

  • @LucasZhang-MSFT 在一段时间内无法接受答案,现已接受。
【解决方案2】:

首先为您的特定数据创建类:

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

    public string message {get; set;}
}

然后制作字典列表:

List<Dictionary<DateTime,JsonContent>> jsonData = new List<Dictionary<DateTime, JsonContent>>();

将数据解析为变量:

jsonData = JsonConvert.DeserializeObject<List<Dictionary<DateTime, JsonContent>>>(yourJSON);

现在你有了所有的数据:

foreach (var item in jsonData)
{
    //your date - item.key;
    //your data inside - item.color and item.message
}

我不确定它会起作用:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-03
    • 2022-01-17
    • 2017-12-23
    • 1970-01-01
    • 2012-08-22
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多