无法将 JSON 字符串反序列化为 C# 对象

Posted

技术标签:

【中文标题】无法将 JSON 字符串反序列化为 C# 对象【英文标题】:Unable to deseralize JSON String to a C# Object 【发布时间】:2021-04-27 10:11:03 【问题描述】:

我正在尝试将从 https://my-json-server.typicode.com/dskato/UDLAProyectoApi/posts 检索到的 JSON 字符串转换为我的“客户”对象列表

数据很好,但是当我尝试反序列化时,没有任何反应,数据不为空,但无法使用 System.Diagnostics.Debug.WriteLine(); 打印它看看发生了什么

我的模型: 客户.cs

 public class Customer

    private CustomerType _customerType;

    public int Id  get; set; 
    public string Name  get; set; 
    public string Title  get; set; 
    public string Phone  get; set; 
    public string Address  get; set; 
    public string Description  get; set; 
    public double Longitude  get; set; 
    public double Latitude  get; set; 
    public DateTime? FullyAttendedTime  get; set; 
    public Geoposition GeoLocation => new Geoposition  Latitude = Latitude, Longitude = Longitude ;
   
    public CustomerStatus CurrentStatus
    
        get
        
            return CustomerStatus.Resolving;
        
    

    public CustomerType CustomerCategory
    
        get  return _customerType; 
        set  _customerType = value; 
    

CustomStatus.cs

public enum CustomerStatus

    AwaitingTaxi = 1,
    Resolving = 2,
    Resolved = 3

CustomerType.cs

   public enum CustomerType

    Business = 1,
    Group = 2,
    Anonymous = 3

我的数据: 数据存储库.cs

 public static class DataRepository


    private static string _content;
    private static IList<Customer> _customerList;

    public static IList<Customer> LoadCustomerData()
    
        //WriteFile();



        return _customerList ?? 
             (_customerList = 
             LoadData<IList<Customer>>(GlobalSetting.CustomerJsonDataFile));
    



    public static async Task WriteFile()
    
        string content = await LoadDataTest();
        _content = content;
        System.Diagnostics.Debug.WriteLine(content);
        System.Diagnostics.Debug.WriteLine("AAAAAAAAAAAAHHHHH");
        


    

    static async Task<string> LoadDataTest()
    
        var request = new HttpRequestMessage();
        request.RequestUri = new System.Uri("https://my-json-server.typicode.com/dskato/UDLAProyectoApi/posts");
        request.Method = HttpMethod.Get;
        request.Headers.Add("Accept", "application/json");
        var client = new HttpClient();

        HttpResponseMessage response = await client.SendAsync(request);

        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        
            string content = await response.Content.ReadAsStringAsync();
            return content;

        
        else
        

            return "";

        



    





    private static T LoadData<T>(string dataFileName)
    


        
        var assembly = typeof(DataRepository).GetTypeInfo().Assembly;
        string preparedDataFileName = string.Format("MyTaxiCompany02.0",
            dataFileName.Replace("/", "."));
        Stream stream = assembly.GetManifestResourceStream(preparedDataFileName);

        if (stream == null)
        
            return default(T);
        

        using (StreamReader sr = new StreamReader(stream))
        
         
            var ret = JsonConvert.DeserializeObject<T>(sr.ReadToEnd());
            System.Diagnostics.Debug.WriteLine("DATAA");
            System.Diagnostics.Debug.WriteLine(ret);
            return ret;

        
      
    

    

所以我尝试的是这样的:

private static T LoadData<T>()

    var ret = JsonConvert.DeserializeObject<T>(_content);
    return ret;
    


public static IList<Customer> LoadCustomerData()
    


        return _customerList ?? 
             (_customerList = 
             LoadData<IList<Customer>>());
    

但什么也没发生

LoadData Original 正在工作,仅从我的项目中的文件读取,但我需要的是读取来自该 Api 的信息

在 LoadDataTest() 方法中工作正常,我在写入文件中调用它们 o 得到这样的字符串:

  
    "Id": 1,
    "Phone": "(555) XXX-XXXX",
    "Name": "Jhon Doe",
    "Title": "Jhon Doe",
    "Address": "Calle Dr. Miguel Ríos Sarmiento, 3, 41020 Sevilla, Spain",
    "Description": "Quick business trip to city center.",
    "UpdateDescription": "",
    "Latitude": -0.1674027763646159,
    "Longitude": -78.47094603889924,
    "CustomerType": 1,
    "Taxis": [
      
        "id": 3
      
    ],
    "CustomerCategory": 1
  ,
  
    "Id": 2,
    "Phone": "(555) XXX-XXXX",
    "Name": "Anna Doe",
    "Title": "Anna Doe",
    "Address": "Av. del Deporte, 33, 41020 Sevilla, Spain",
    "Description": "You need to go to the nearest hospital.",
    "UpdateDescription": "",
    "Latitude": -0.1698626865861518,
    "Longitude": -78.47514771904376,
    "Taxis": [
      
        "id": 3
      
    ],
    "CustomerCategory": 2
  ,
  
    "Id": 3,
    "Phone": "(555) XXX-XXXX",
    "Name": "Jhon Doe",
    "Title": "Jhon Doe",
    "Address": "Calle Dr. Miguel Ríos Sarmiento, 3, 41020 Sevilla, Spain",
    "Description": "Quick business trip to city center.",
    "UpdateDescription": "",
    "Latitude": -0.16288897268889635,
    "Longitude": -78.47435378522721,
    "CustomerType": 1,
    "Taxis": [
      
        "id": 3
      
    ],
    "CustomerCategory": 3
  
] ``` 

【问题讨论】:

尽量减少重现问题的代码。 【参考方案1】:

给定

public class SomeFunkyClass

   public int Id  get; set; 
   public string Phone  get; set; 
   public string Name  get; set; 
   public string Title  get; set; 
   public string Address  get; set; 
   public string Description  get; set; 
   public string UpdateDescription  get; set; 
   public float Latitude  get; set; 
   public float Longitude  get; set; 
   public int CustomerType  get; set; 
   public Taxi[] Taxis  get; set; 
   public int CustomerCategory  get; set; 


public class Taxi

   public int id  get; set; 

你只需调用

var results = JsonConvert.DeserializeObject<SomeFunkyClass[]>(input);

// or

var results = JsonConvert.DeserializeObject<List<SomeFunkyClass>>(input);

关于WriteLine问题,

foreach (var item in result)
   Console..WriteLine($"id : item.Id, Name : item.Name...");

输出

id : 1, Name : Jhon Doe..
id : 2, Name : Anna Doe..
id : 3, Name : Jhon Doe..

【讨论】:

以上是关于无法将 JSON 字符串反序列化为 C# 对象的主要内容,如果未能解决你的问题,请参考以下文章

C# JSON 将文件反序列化为对象列表失败,并将字符串转换为集合错误

将 JSON 字符串反序列化为多个 C# 对象

在调用API后,将JSON对象反序列化为C#类[重复]。

将 JSON 反序列化为 C# 对象以在网格中将嵌套数组显示为字符串

将Json字符串反序列化为对象java

无法在 C# 中反序列化 JSON 结果。输入字符串格式不正确错误