如何使用C#正确反序列化JSON对象

问题描述 投票:0回答:1

我正在尝试反序列化包含国家/地区列表的json对象,但我不断收到读取以下内容的错误

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

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

这是我用来获取国家/地区列表并将其绑定到一个countrysList模型的方法

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个回答
0
投票

尝试一下:

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

                    return countriesObj;
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.