【问题标题】:Cannot deserialize Json String to List Object无法反序列化 Json 字符串以列出对象
【发布时间】:2014-11-20 06:33:22
【问题描述】:

我有一个这样的 json 字符串:

{"bwEventList": {

    "events": [

      {
        "summary" : "Leisure Classes Beginning Today",
        "subscriptionId" : "",
        "calPath" : "%2Fpublic%2Fcals%2FMainCal",
        "guid" : "CAL-02a786e6-45f207c3-0147-11c6cf10-000074e3bedework%40lsu.edu",
        "recurrenceId" : "",
        "link" : "",
        "eventlink" : "http://calendar.apps.lsu.edu/feeder/feeder/event/eventView.do?b=de&calPath=%2Fpublic%2Fcals%2FMainCal&guid=CAL-02a786e6-45f207c3-0147-11c6cf10-000074e3bedework%40lsu.edu&recurrenceId=",
        "status" : "CONFIRMED",
        "start" : {
          "allday" : "true",
          "shortdate" : "11/22/14",
          "longdate" : "November 22, 2014",
          "dayname" : "Saturday",
          "time" : "12:00 AM",
          "utcdate" : "20141122T060000Z",
          "datetime" : "20141122",
          "timezone" : ""
        },
        "end" : {
          "allday" : "true",
          "shortdate" : "11/22/14",
          "longdate" : "November 22, 2014",
          "dayname" : "Saturday",
          "time" : "12:00 AM",
          "utcdate" : "20141122T060000Z",
          "datetime" : "20141122",
          "timezone" : ""
        }

我的模型是这样写的:

    public class Event
{
    [JsonProperty(PropertyName ="summary")]
    public string summary { get; set; }
    [JsonProperty(PropertyName ="subscriptionId")]
    public string subscriptionId { get; set; }
    [JsonProperty(PropertyName ="calPath")]
    public string calPath { get; set; }
    [JsonProperty(PropertyName ="guid")]
    public string guid { get; set; }
    [JsonProperty(PropertyName ="reccurenceId")]
    public string recurrenceId { get; set; }
    [JsonProperty(PropertyName ="link")]
    public string link { get; set; }
    [JsonProperty(PropertyName ="eventlink")]
    public string eventlink { get; set; }
    [JsonProperty(PropertyName ="status")]
    public string status { get; set; }
    [JsonProperty(PropertyName ="start")]
    public Start start { get; set; }
    [JsonProperty(PropertyName ="end")]
    public End end { get; set; }
    [JsonProperty(PropertyName ="location")]
    public Location location { get; set; }
    [JsonProperty(PropertyName ="contact")]
    public Contact contact { get; set; }
    [JsonProperty(PropertyName ="calendar")]
    public Calendar calendar { get; set; }
    [JsonProperty(PropertyName ="categories")]
    public List<string> categories { get; set; }
    [JsonProperty(PropertyName ="description")]
    public string description { get; set; }
    [JsonProperty(PropertyName ="cost")]
    public string cost { get; set; }

}

public class BwEventList
{
    public List<Event> events { get; set; }
}

    public class Start
    {
        [JsonProperty(PropertyName ="allday")]
        public string allday { get; set; }
        [JsonProperty(PropertyName ="shortdate")]
        public string shortdate { get; set; }
        [JsonProperty(PropertyName ="longdate")]
        public string longdate { get; set; }
        [JsonProperty(PropertyName ="dayname")]
        public string dayname { get; set; }
        [JsonProperty(PropertyName ="time")]
        public string time { get; set; }
        [JsonProperty(PropertyName ="utcdate")]
        public string utcdate { get; set; }
        [JsonProperty(PropertyName ="datetime")]
        public string datetime { get; set; }
        [JsonProperty(PropertyName ="timezone")]
        public string timezone { get; set; }
    }

    public class End
    {
        public string allday { get; set; }
        public string shortdate { get; set; }
        public string longdate { get; set; }
        public string dayname { get; set; }
        public string time { get; set; }
        public string utcdate { get; set; }
        public string datetime { get; set; }
        public string timezone { get; set; }
    }

我试图反序列化字符串,然后将列表中的每个事件显示到 XML(android) 上。下面是我如何获取字符串并反序列化它

public async Task<List<ReveilleApp.Core.Models.Event>> GetItems(string feedUrl)
    {
        try{
        using (WebClient webclient = new WebClient ()) {
            WebClient n = new WebClient ();

            var json =  await n.DownloadStringTaskAsync (feedUrl);

            var model = JsonConvert.DeserializeObject<List<ReveilleApp.Core.Models.Event>>(json);

            return model;
            }
        }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;

            }


        }

返回项目以填充列表视图。在异常我得到这个错误

    Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ReveilleApp.Core.Models.Event]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

我尝试了很多解决方案,但都没有成功

【问题讨论】:

    标签: c# android listview xamarin json.net


    【解决方案1】:

    您的模型与 Json 列不匹配。

    Leonel 更正了模型:

    但我也想建议对您的方法进行一些更正:

    public async Task<RootObject> GetItems(string feedUrl)
    {
            try
            {
                using (WebClient webclient = new WebClient()) 
                {
                     var json =  await webclient.DownloadStringTaskAsync(feedUrl);
                     var model = JsonConvert.DeserializeObject<RootObject>(json);
                     return model;
                }
            }
            catch(Exception ex)
            {
                    Console.WriteLine(ex.Message);
                    return null;
            }
    }
    

    您也可以将其作为列表来获取。

    当你调用这个方法时

    var root = GetItems(string feedUrl) as RootObject; // Ex call for method
    if(root != null && root.bwEventList != null && root.bwEventList.Count > 0) // Just checking the conditions to make sure everthing is OK.
    {
         List<Event> eventsList = root.bwEventList.events; // Here you will get it as a list.
    }
    

    【讨论】:

    • 无法将其作为列表返回?我正在尝试填充 ListView
    • 是的,您也可以将其作为列表获取。查看我的更新。
    • 您的两个答案都有帮助!谢谢
    【解决方案2】:

    您的模型是问题,因为它与您的JSON 不同,我重新创建了您的模式。

    尝试设置和使用这个模型:

    public class Start
    {
        public string allday { get; set; }
        public string shortdate { get; set; }
        public string longdate { get; set; }
        public string dayname { get; set; }
        public string time { get; set; }
        public string utcdate { get; set; }
        public string datetime { get; set; }
        public string timezone { get; set; }
    }
    
    public class End
    {
        public string allday { get; set; }
        public string shortdate { get; set; }
        public string longdate { get; set; }
        public string dayname { get; set; }
        public string time { get; set; }
        public string utcdate { get; set; }
        public string datetime { get; set; }
        public string timezone { get; set; }
    }
    
    public class Event
    {
        public string summary { get; set; }
        public string subscriptionId { get; set; }
        public string calPath { get; set; }
        public string guid { get; set; }
        public string recurrenceId { get; set; }
        public string link { get; set; }
        public string eventlink { get; set; }
        public string status { get; set; }
        public Start start { get; set; }
        public End end { get; set; }
    }
    
    public class BwEventList
    {
        public List<Event> events { get; set; }
    }
    
    public class RootObject
    {
        public BwEventList bwEventList { get; set; }
    }
    

    【讨论】:

    • 是的,这不起作用,json 字符串比示例 btw 大得多。我真的需要反序列化所有对象吗?我首先从 json2charp 得到了我的模型,但是有一些奇怪的属性给我带来了问题
    • 如果确实有帮助,请接受它作为答案。 :)
    • @Cubatown 如果需要,您可以删除RootObject 并改用BWEventList。您也可以使用[JsonProperty("name")] 代替[JsonProperty(PropertyName ="name")]
    • 在 RJK 的回答之后让它工作了,你的模型也有帮助。赞成
    猜你喜欢
    • 1970-01-01
    • 2021-04-27
    • 2021-01-16
    • 2019-02-05
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    相关资源
    最近更新 更多