【问题标题】:Can't de-serialize the current JSON object, error in xamarin.forms无法反序列化当前 JSON 对象,xamarin.forms 中的错误
【发布时间】:2017-10-04 09:31:12
【问题描述】:

我在我的 Xamarin.forms 应用程序中发出 Api 请求,该请求是显示商店列表,但它引发以下异常: 无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[LoyaltyWorx.Page1+Store]”,因为该类型需要 JSON 数组(例如 [1, 2,3]) 正确反序列化。

Json 响应:

{
    "Credentials": {
        "Token": "K6Zi8VXfqWuthxgn3YEfrU6Bj/EKM7BqvSZcatFgvMx408yadbE+Qj6IuTnZ++C9q4Ty1W2f1quNYMKZxFBNZg==",
        "Authenticated": true,
        "SecretKey": null
    },
    "Companies": [
        {
            "CustomerID": 2,
            "CompanyName": "Posworx",
            "CompanyLogo": "\Images\\Capture.JPG",
            "Stores": [
                {
                    "StoreID": 2,
                    "StoreNumber": null,
                    "StoreName": "Pos Store",
                    "StoreAddress": "218 Stamford Hill Road",
                    "StoreCity": "Durban",
                    "StoreRegion": "KZN",
                    "StoreCountry": "South Africa"
                },
                {
                    "StoreID": 4,
                    "StoreNumber": null,
                    "StoreName": "Pos Store",
                    "StoreAddress": "218 Mathews Meyiwa Road",
                    "StoreCity": "Durban",
                    "StoreRegion": "KZN",
                    "StoreCountry": "South Africa"
                }
]
        },

Xamarin.Forms 中的类:

 public class Store
        {
            public List<Company> companies { get; set; }
            public int StoreID { get; set; }
            public object StoreNumber { get; set; }
            public string StoreName { get; set; }
            public string StoreAddress { get; set; }
            public string StoreCity { get; set; }
            public string StoreRegion { get; set; }
            public string StoreCountry { get; set; }
        }
        public class Credentials
        {
            public string Token { get; set; }
            public bool Authenticated { get; set; }
            public object SecretKey { get; set; }
        }
        public class Company
        {
            public int CustomerID { get; set; }
            public string CompanyName { get; set; }
            public string CompanyLogo { get; set; }
            public IList<Store> Stores { get; set; }
        }

        public class Stores
        {
            public Credentials Credentials { get; set; }
            public IList<Company> Companies { get; set; }
            public bool IsError { get; set; }
            public object ErrorMessage { get; set; }
        }

加载和反序列化响应的代码:

public async void LoadData()
{
    try
    {
        var content = "";
        HttpClient client = new HttpClient();
        var RestUrl = "/api/Company/GetCustomerCompanies";
        client.BaseAddress = new Uri(RestUrl);

        client.DefaultRequestHeaders.Add("X-Giftworx-App", "K6Zi8VXfqWuthxgn3YEfrU6Bj/EKM7BqvSZcatFgvMx408yadbE+Qj6IuTnZ++C9q4Ty1W2f1quNYMKZxFBNZg==");
        HttpResponseMessage response = await client.GetAsync(RestUrl);
        content = await response.Content.ReadAsStringAsync();
        var Items = JsonConvert.DeserializeObject<List<Store>>(content);
        MainListView.ItemsSource = Items;
    }


    catch (Exception ex)
    {
        string exception = ex.Message;
    }

}

目标是在 ListView 中显示 CompanyName 和 CompanyLogo:Xaml:

<ListView Grid.Column="0" Grid.Row="0"
                  x:Name="MainListView"
                  HasUnevenRows="True" 
                  VerticalOptions="FillAndExpand"
                  HorizontalOptions="FillAndExpand"
                  ItemTapped="MainListView_ItemTapped" 
                  SeparatorColor="DarkGray">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ImageCell ImageSource="{Binding CompanyLogo}" 
                               Text="{Binding CompanyName}" 
                               TextColor="Black"
                              />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

【问题讨论】:

    标签: xaml xamarin xamarin.forms httpclient webclient


    【解决方案1】:

    您正在尝试将 JSON 序列化为 List&lt;Store&gt;。无论如何,您提供的 JSON 不是数组(如例外所述),而是单个 Store。您必须将其反序列化为 Store 对象才能正常工作。

    使用 Json.NET,您可以实现这一目标

    var store = JsonConvert.DeserializeObject<Store>(jsonResponse);
    

    编辑:

    在尝试更好地理解你的 sn-ps 之后,我得出了结论,

    var stores = JsonConvert.DeserializeObject<Stores>(jsonResponse); 
    

    可能比第一个 sn-p 更符合您的需要。 JSON 响应看起来更像 Stores 类而不是 Store 类。

    编辑 2:

    JSON 不正确,我删除了末尾的逗号并添加了 ]} 以使其有效。

    {
        "Credentials": {
            "Token": "K6Zi8VXfqWuthxgn3YEfrU6Bj/EKM7BqvSZcatFgvMx408yadbE+Qj6IuTnZ++C9q4Ty1W2f1quNYMKZxFBNZg==",
            "Authenticated": true,
            "SecretKey": null
        },
        "Companies": [{
                "CustomerID": 2,
                "CompanyName": "Posworx",
                "CompanyLogo": "\Images\\Capture.JPG",
                "Stores": [{
                        "StoreID": 2,
                        "StoreNumber": null,
                        "StoreName": "Pos Store",
                        "StoreAddress": "218 Stamford Hill Road",
                        "StoreCity": "Durban",
                        "StoreRegion": "KZN",
                        "StoreCountry": "South Africa"
                    }, {
                        "StoreID": 4,
                        "StoreNumber": null,
                        "StoreName": "Pos Store",
                        "StoreAddress": "218 Mathews Meyiwa Road",
                        "StoreCity": "Durban",
                        "StoreRegion": "KZN",
                        "StoreCountry": "South Africa"
                    }
                ]
            }
        ]
    }
    

    将这个固定的 JSON 反序列化为 Stores(第二个 sn-p)对我有用。

    【讨论】:

    • 感谢 Paul,我尝试了您的建议,但仍然抛出相同的异常错误。
    • 同样的例外?奇怪的。当我找到时间时,我会将它破解到 LINQpad 中并查看一下。
    • 是的,同样的例外:(。非常感谢,我很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    相关资源
    最近更新 更多