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 上显示内容,因此需要额外的实现吗?

解决方法

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; }
}

这就是您的日历事件的外观。您可以将字符串更改为 DateTime。

此示例 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; }
}
,

我咨询了后端团队,他们更改了 JSON 响应,如下所示:

{
    "calendarEvents": [
        {
            "day": "20210503","list": [
                {
                    "title": "Event 3","description": "Event 3"
                }
            ]
        },{
            "day": "20210504","description": "Event 3"
                },{
                    "title": "Event 4","description": "Event 4"
                }
            ]
        },{
            "day": "20210505","description": "Event 4"
                },{
                    "title": "Event 5","description": "Event 5"
                }
            ]
        }
    ]
}

对应的模型类:

public class List
{
    public string title { get; set; }
    public string description { get; set; }
}

public class CalendarEvent
{
    public string day { get; set; }
    public List<List> list { get; set; }
}

public class Root
{
    public List<CalendarEvent> calendarEvents { get; set; }
}

现在我可以解析数据并将其显示在扩展器上。

谢谢

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...