当属性名称包含空格和保留字时,将 JSON 映射到 C# 类

本文关键字:JSON 映射 保留字 属性 包含 空格 | 更新日期: 2023-09-27 17:57:14

我正在使用REST API服务。在服务响应 JSON 中,存在包含空格和保留字的属性名称。我正在尝试将其映射到 C# 类,但我无法分配与字段名称相同的属性名称。

目前,仅当字段的 JSON 属性和 C# 类名完全匹配时,映射才会成功,否则值显示为 null

下面是从服务返回的 JSON:

{
   "value": [   {
      "accountNo": "JKBXXXXXXXXXVNX1",
      "mainSalesPerson": "XXXXX",
      "accountName": "XXXXXX",
      "ledgerBalance": "-2,298.70",
      "T+3": "0.00",
      "T+4": "0.00",
      "T+5 and Above": "2,298.70",
      "riskRatedPortfolioValue": "109,057.50",
      "exposure": "106,758.80",
      "costToFirm": "",
      "incomeToFirm": "14.59",
      "costToIncome(%)": "",
      "exposure(%)": "2.11",
      "O/S Balance": "-2,298.70"
   }],
   "success": true
}

我使用了以下映射类:

public class CountObject
{
    public string value { get; set; }
    public string success { get; set; }
}
public class RiskManagementQueryValueObject
{
    public string accountNo { get; set; }
    public string mainSalesPerson { get; set; }
    public string accountName { get; set; }
    public string ledgerBalance { get; set; }
    [SerializeAs(Name = "T+3")]
    public string T3 { get; set; }
    [SerializeAs(Name = "T+4")]
    public string T4 { get; set; }
    [SerializeAs(Name = "T+5 and Above")]
    public string T5_and_Above { get; set; }
    public string riskRatedPortfolioValue { get; set; }
    public string exposure { get; set; }
    public string costToFirm { get; set; }
    public string incomeToFirm { get; set; }
    [SerializeAs(Name = "costToIncome(%)")]
    public string costToIncome { get; set; }
    [SerializeAs(Name = "exposure(%)")]
    public string exposure_per { get; set; }
    [SerializeAs(Name = "O/S Balance")]
    public string OS_Balance { get; set; }
}
public class RiskManagementQueryHeadertObject
{
    public List<RiskManagementQueryValueObject> value { get; set; }
    public bool success { get; set; }
}

这是我与服务交谈的方式:

public List<RiskManagementQueryValueObject> getOverdues()
{
    List<RiskManagementQueryValueObject> overdues = new List<RiskManagementQueryValueObject>();
    var count = 0.0;
    try
    {
        var restProxy = new RESTProxy();
        var request = restProxy.initRestRequest("/cam/riskmanagement/1/query/count", Method.POST, new { requestCriteriaMap = new { currency = "LKR" } });
        CountObject data = restProxy.Execute<CountObject>(request);
        if (data.success.ToString().ToLower() != "true")
            return null;
        //get the page count
        var pageCount = Math.Truncate(count / 300) + 1;
        for (int j = 0; j < pageCount; j++)
        {
            var request2 = restProxy.initRestRequest(string.Format("/cam/riskmanagement/1/query/{0}", (j + 1).ToString()), Method.POST, new { requestCriteriaMap = new { currency = "LKR" } });
            RiskManagementQueryHeadertObject data2 = restProxy.Execute<RiskManagementQueryHeadertObject>(request2);
            overdues.AddRange(data2.value);
        }
    }
    catch (Exception)
    {
        overdues = null;
    }
    return overdues;
}
public class RESTProxy
{
    string DEFAULT_HOST = "http://xxx.xxx.xxx.xxx:xxx/";
    string DEFAULT_MODULE = "xxx-rest";
    string DEFAULT_USER = "xxx:xxx:xxx";
    string DEFAULT_PASS = "xxx";
    public T Execute<T>(RestRequest request) where T : new()
    {
        var client = new RestClient(string.Concat(DEFAULT_HOST, DEFAULT_MODULE))
        {
            Authenticator = new DigestAuthenticator(DEFAULT_USER, DEFAULT_PASS, DEFAULT_HOST)
        };
        var response = client.Execute<T>(request);
        if (response.ErrorException != null)
        {
            throw response.ErrorException;
        }
        return response.Data;
    }
    public RestRequest initRestRequest(string pRestResourceName, Method pRestServiceVerb, object pRestRequestBody)
    {
        var request = new RestRequest(pRestResourceName, pRestServiceVerb);
        request.RequestFormat = DataFormat.Json;

        if (pRestRequestBody != null)
        {
            request.AddBody(pRestRequestBody);
        }
        return request;
    }
}

如何解决此问题并将所有字段序列化到我的类定义中?

当属性名称包含空格和保留字时,将 JSON 映射到 C# 类

使用 JsonProperty 属性对我有用:

例:

此 C# 类:

public class Product
{
    [JsonProperty(PropertyName = "Name/ + 1")]
    public string Name { get; set; }
}

映射到以下 JavaScript 对象:

var input = {"Name/ + 1": "PostName"};

我解决了这个问题。我添加了[DeserializeAs(Name ="")]而不是[SerializeAs(Name ="")].我刚刚在我的 C# Map 类中做了这个:

public class RiskManagementQueryValueObject
    {
        public string accountNo { get; set; }
        public string mainSalesPerson { get; set; }
        public string accountName { get; set; }
        public string ledgerBalance { get; set; }
        [DeserializeAs(Name = "T+3")]
        public string T3 { get; set; }
        [DeserializeAs(Name = "T+4")]
        public string T4 { get; set; }
        [DeserializeAs(Name = "T+5 and Above")]
        public string T5_and_Above { get; set; }
        public string riskRatedPortfolioValue { get; set; }
        public string exposure { get; set; }
        public string costToFirm { get; set; }
        public string incomeToFirm { get; set; }
        [DeserializeAs(Name = "costToIncome(%)")]
        public string costToIncome { get; set; }
        [DeserializeAs(Name = "exposure(%)")]
        public string exposure_per { get; set; }
        [DeserializeAs(Name = "O/S Balance")]
        public string OS_Balance { get; set; }
    }