【问题标题】:How to correctly deserialise a JSON object correctly using C#如何使用 C# 正确反序列化 JSON 对象
【发布时间】:2023-03-30 16:49:01
【问题描述】:

我正在尝试反序列化一个包含国家/地区列表的 json 对象,但我不断收到错误消息

类型 System.String' 不支持数组的反序列化。

我能够从 API 中检索 JSON 对象(国家列表),但是当我尝试反序列化 JSON 对象时

这是我获取国家列表并将它们绑定到国家列表模型的方法

public List<CountriesList> GetCountries()
            {
                try
                {                     
                    string apiCountriesUrl = "https://restcountries.eu/rest/v2/all"; 
                    string response = GetServiceCallByUrl(apiCountriesUrl);
                    var countriesObj = System.Web.Helpers.Json.Decode<List<CountriesList>>(response);

                    return countriesObj;
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }

我的国家列表模型

  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

namespace ApplicationPortal.Models
{
    public class CountriesList
    {
        public string name { get; set; }
        public string callingCodes { get; set; }
    }
}

【问题讨论】:

标签: c# json asp.net-mvc rest deserialization


【解决方案1】:

dotnetfiddle

参见上面的代码。

我使用 quicktype.io 来获取来自 api 调用的 json 的 POCO 类

你得到的错误是因为 callCodes 是一个字符串列表,在您的模型中它是一个字符串

public List<string> CallingCodes { get; set; }

更新您的模型,使其反映 json 模型

或使用像我使用的模型生成器。

我的代码使用 Newtonsoft.Json 包,因为 quicktype.io 使用它,您可以修改它并使模型仅限于您需要的字段,您应该能够使用 System.Web.Helpers.Json.Decode 就像你现在使用的一样。

【讨论】:

    【解决方案2】:

    callingCodes 是一个字符串数组,把你的模型改成public List&lt;string&gt; callingCodes { get; set; }

    【讨论】:

      【解决方案3】:

      我建议从您的数据中自动生成所需的类:

      复制您要导入的 json 示例,然后在 Visual Studio 中选择 Edit/Paste Special/Paste classes as Json。

      这将生成允许正确导入 json 的类,无需任何猜测。

      有在线版本可以生成更好的代码:https://app.quicktype.io/?l=csharp

      【讨论】:

        【解决方案4】:

        在尝试此操作之前,您需要添加 Newtonsoft.dll 引用:

        public List<CountriesList> GetCountries()
                    {
                        try
                        {                     
                            string apiCountriesUrl = "https://restcountries.eu/rest/v2/all"; 
                            string response = GetServiceCallByUrl(apiCountriesUrl);
                            var countriesObj = JsonConvert.DeserializeObject<List<CountriesList>>(response);
        
                            return countriesObj;
                        }
                        catch (Exception exception)
                        {
                            throw exception;
                        }
                    }
        

        【讨论】:

        • 请解释您的代码的作用。不建议使用纯代码答案
        • 将响应字符串反序列化为 CountryList 列表
        • 您基本上给出了与 OP 相同的代码,并要求他包含一个他可能需要也可能不需要的 DLL。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-13
        • 2021-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多