You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6中JsonConvert.DeserializeObject反序列化空结果求助

ASP.NET Core 6中JsonConvert反序列化Company模型为空的解决办法

问题场景

在ASP.NET Core 6项目中调用API后,使用JsonConvert.DeserializeObject<company>反序列化响应内容,得到的company对象始终为空。确认API返回状态码为200且响应数据格式正确,但无法完成模型映射。

相关代码与数据

反序列化代码

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
    string apiResponse = await response.Content.ReadAsStringAsync();
    company = JsonConvert.DeserializeObject<company>(apiResponse);
}

Company模型定义

public class company
{
    public string bankAccount { get; set; } = string.Empty;
    public string bankName { get; set; } = string.Empty;
    public string cif { get; set; } = string.Empty;

    public string creationDate { get; set; } = string.Empty;
    public string email { get; set; } = string.Empty;
    public string fiscalAttribute { get; set; } = string.Empty;
    public string id { get; set; } = string.Empty;

    public string locationAddress { get; set; } = string.Empty;
    public string locationCounty { get; set; } = string.Empty;
    public string name { get; set; } = string.Empty;
    public string nrRegCom { get; set; } = string.Empty;

    public string passwordHash { get; set; } = string.Empty;
    public string phoneNumber { get; set; } = string.Empty;
    public string privilegeKey { get; set; } = string.Empty;

    public string registrationState { get; set; } = string.Empty;
    public string storedHardwareID { get; set; } = string.Empty;

    public string subscriptionExpirationDate { get; set; } = string.Empty;
    public string subscriptionID { get; set; } = string.Empty;
    public string actionConfirmationID { get; set; } = string.Empty;
    public string updateDate { get; set; } = string.Empty;
}

API返回的JSON数据

{
    "company": {
        "bankAccount": "777",
        "bankName": "777",
        "cif": "123",
        "creationDate": "2023-01-16T17:38:45.962Z",
        "email": "pankaj@gmail.com",
        "fiscalAttribute": "123",
        "id": "f0e3bfef5bcf40c987713153e55dceef",
        "locationAddress": "india",
        "locationCounty": "india",
        "name": "pankaj",
        "nrRegCom": "123",
        "passwordHash": "7c78eea7a591b0c8a4dad680372e35ca12e11cffdac5c69a39700c8014fbcc82",
        "phoneNumber": "88888858",
        "privilegeKey": "",
        "registrationState": 1,
        "storedHardwareID": "",
        "subscriptionExpirationDate": "0001-01-01T00:00:00Z",
        "subscriptionID": "",
        "actionConfirmationID": "",
        "updateDate": "2023-01-16T17:38:45.962Z"
    }
}

问题原因

  1. JSON结构不匹配:API返回的JSON是一个外层对象,包含名为company的属性,而直接反序列化到company类型时,Json.NET无法找到匹配的根对象结构,导致返回空实例。
  2. 类型不匹配:模型中registrationState定义为string类型,但API返回的是数值1,类型不兼容可能引发静默反序列化失败(取决于Json.NET配置)。

解决办法

方法1:创建包装类匹配JSON结构

定义一个外层响应类,对应API返回的JSON结构:

public class CompanyResponse
{
    public company company { get; set; }
}

修改反序列化代码:

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
    string apiResponse = await response.Content.ReadAsStringAsync();
    var responseObj = JsonConvert.DeserializeObject<CompanyResponse>(apiResponse);
    company = responseObj?.company;
}

方法2:直接解析JObject提取目标对象

无需新增类,使用JObject直接提取内部的company节点:

using Newtonsoft.Json.Linq;

// ...
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
    string apiResponse = await response.Content.ReadAsStringAsync();
    var jsonObj = JObject.Parse(apiResponse);
    company = jsonObj["company"].ToObject<company>();
}

修复类型不匹配问题

将模型中的registrationState类型改为int(推荐,因为API返回的是数值):

public int registrationState { get; set; }

如果必须保留string类型,可以添加类型转换特性:

[JsonConverter(typeof(ToStringConverter))]
public string registrationState { get; set; } = string.Empty;

(需要自定义ToStringConverter实现,或使用已有的类型转换转换器)

额外建议

  • 开启Json.NET的反序列化错误提示,便于排查问题:
var settings = new JsonSerializerSettings
{
    Error = (sender, args) =>
    {
        // 打印或记录错误信息
        Console.WriteLine(args.ErrorContext.Error.Message);
        args.ErrorContext.Handled = true;
    }
};
company = JsonConvert.DeserializeObject<company>(apiResponse, settings);

内容的提问来源于stack exchange,提问作者Pankaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:45:24