首页 > 解决方案 > Xamarin Forms:如何在没有稳定密钥的情况下解析 JSON 响应?

问题描述

Newtonsoft.Json用来解析我的回复。但是对于以下响应,我不知道如何创建模型类以及如何在扩展器上显示它。

我的回复:

{
"calendarEvents": {
        "2021-05-03T05:00:00.000+0000": [
            {
                "title": "Event 2",
                "description": "Event 2"
            }
        ],
        "2021-05-04T05:00:00.000+0000": [
            {
                "title": "Event 3",
                "description": "Event 3"
            }
        ],
        "2021-05-05T05:00:00.000+0000": [
            {
                "title": "Event 3",
                "description": "Event 3"
            },
            {
                "title": "Event 4",
                "description": "Event 4"
            }
        ]
    }
}

我尝试了如下方法:

public class MyEvents
{
    public List<calendarEvents> calendarEvents { get; set; }
}

public class calendarEvents
{
    //What will be here? it is also a list and it has no stable key
}

public class Dummy//(Top class name here)
{
    public string title { get; set; }
    public string description { get; set; }
}

2021-05-03T05:00:00.000+0000我可以添加到模型类中而不是这个?响应是另一个列表中的项目列表。计划使用扩展器在 UI 上显示这个,所以需要额外的实现吗?

标签: jsonxamarin.formsexpander

解决方案


public class calendarEvents
{
    public Dictionary<string, List<Dummy>> item {get; set;}
}

public class Dummy//(Top class name here)
{
    public string title { get; set; }
    public string description { get; set; }
}

这就是您的 calendarEvents 的外观。您可以将字符串更改为日期时间。

此示例 JSON 的模型很糟糕,它应该如下所示:

public class MyEvents
{
    [JsonProperty("calendarEvents")]
    public Dictionary<string, List<CalendarEvent>> calendarEvents{ get; set; }
}

public class CalendarEvent
{
    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }
}

推荐阅读