【问题标题】:Cannot deserialize the current JSON object - Newtonsoft无法反序列化当前 JSON 对象 - Newtonsoft
【发布时间】:2017-03-06 07:32:57
【问题描述】:

我在解决此错误消息时遇到问题。我在这里查看了其他一些答案并更改了一些内容,但我仍然收到此错误:

Newtonsoft.Json.JsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[Clocker.Models.PeopleLocationForUser]”,因为类型需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。

这是我的课:

namespace Clocker.Models
{
    public class PeopleLocationForUser
    {
        string locationPeople { get; set; }
        public users users { get; set; }

    }

    public class users
    {
        public int EB_Counter { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int TATokenValue { get; set; }
    }
}

这是反序列化行出错的方法:

public static async Task<PeopleLocationForUser> GetPeopleLocationForUser(string UserName, int LocationId)
{
    Uri uri = new Uri(URL + "GetPeopleLocationForUser" + "?username=" + UserName + "&locationid=" + LocationId);

    HttpClient myClient = new HttpClient();
    var response = await myClient.GetAsync(uri);

    var content = await response.Content.ReadAsStringAsync();

    var test = JsonConvert.DeserializeObject<List<PeopleLocationForUser>>(content);

    //return something when it's working
    return null;
}

这是Json数据的开始:

{"result":true,"locationPeople":[{"EB_Counter":101,"FirstName":"RSS","LastName":"13.11.1","TATokenValue":"TS_101_1_RSS_SWIPE"},{ "EB_Counter":102,"FirstName":"RSS","LastName":"13.11.2","TATokenValue":"TS_102_1_RSS_SWIPE"},{"EB_Counter":93,"FirstName":"RSS","LastName ":"13.7.1","TATokenValue":"TS_93_1_RSS_SWIPE"},{"EB_Counter":94,"FirstName":"RSS","LastName":"13.7.10","TATokenValue":"TS_94_1_RSS_SWIPE"} ,{"EB_Counter":95,"FirstName":"RSS","LastName":"13.8.2","TATokenValue":"TS_95_1_RSS_SWIPE"},{"EB_Counter":99,"FirstName":"RSS", "LastName":"13.9.2","TATokenValue":"TS_99_1_RSS_SWIPE"},

这是我的 Json 数据到达时的样子:

希望你能帮上忙。最终结果是我试图将这些数据放入一个列表中,以便我可以在 Xamarin ListView 中使用它。

【问题讨论】:

  • 据我所知,它需要一个数组而不是一个列表
  • 我想你会在这里找到解决方案:stackoverflow.com/questions/10534576/json-net-deserializing
  • @mcNets 我试过了,但没有改善。我认为我的问题可能与类的构造方式有关,可能与 Json 格式发生冲突,但我不确定。
  • 尝试将您的 JSon 粘贴到 json2csharp.com 并查看它生成的类
  • 也许发布一些 JSON 文件的文本会有所帮助。

标签: class xamarin json.net deserialization


【解决方案1】:

您正在接收列表,并且在类中您只期望一个用户实例,这就是类应该是这样的:

public class LocationPeople
{
    public int EB_Counter { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string TATokenValue { get; set; }
}

public class RootObject
{
    public bool result { get; set; }
    public List<LocationPeople> locationPeople { get; set; }
}

var test = JsonConvert.DeserializeObject<RootObject>(content);

【讨论】:

  • 您好,我实施了您的更改,但仍然收到相同的错误。
猜你喜欢
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
相关资源
最近更新 更多