Newtonsoft DeserializeObject不调用构造函数

时间:2018-01-17 08:52:17

标签: c# json json.net

我遇到了正确反序列化十进制值的问题。该网站的一个建议是使用构造函数,但它没有调用该构造函数。

这是JSON:

{
    "errors": false,
    "response": {
        "entities": [
        {
            "currency_id": "1",
            "balance": 1e-8,
            "address": ""
        },
        {
            "currency_id": "2",
            "balance": 0,
            "address": null
        },
        {
            "currency_id": "3",
            "balance": 0.09865566,
            "address": null
        },
        {
            "currency_id": "5",
            "balance": 0,
            "address": null
        },
        {
            "currency_id": "6",
            "balance": 0,
            "address": null
        }]
    },
    "pagination": {
        "items_per_page": 100,
        "total_items": 5,
        "current_page": 1,
        "total_pages": 1
   }
}

我的课程:

public class ApiResponse<T> where T : class
{
    public bool Errors { get; set; }
    public T Response { get; set; }
}

public class ApiPagingResponse<T> : ApiResponse<T> where T : class
{
    public Pagination Pagination { get; set; }
}

public class GetBalanceListResponse
{
    public GetBalanceListResponseEntity Entity { get; set; }
}

[JsonObject]
public class GetBalanceListResponseEntity
{

    [JsonConstructor]
    public GetBalanceListResponseEntity([JsonProperty("currency_id")]string currencyId, [JsonProperty("balance")]string balance, [JsonProperty("address")]string address)
    {
        CurrencyId = currencyId;
        Balance = decimal.Parse(balance, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint,
            CultureInfo.InvariantCulture);
        Address = address;
    }

    [JsonProperty("currency_id")]
    public string CurrencyId { get; set; }

    [JsonProperty("balance")]
    public decimal Balance { get; set; }

    [JsonProperty("address")]
    public string Address { get; set; }
}

我用它来称呼它:

 var result = JsonConvert.DeserializeObject<ApiPagingResponse<GetBalanceListResponse>>(stringResult);

stringResult是我想要去学习的json字符串。

目前它只为响应的Entity属性返回null。我的所有其他序列化都适用于此方法,问题在于"balance": 1e-8,

是否有人处理过类似问题并对此有所帮助?

1 个答案:

答案 0 :(得分:1)

您正确使用[JsonConstructor]。您唯一的问题是,在GetBalanceListResponse中,方法

public GetBalanceListResponseEntity Entity { get; set; } 

应该是

public List<GetBalanceListResponseEntity> Entities { get; set; }

这是因为在JSON中,相应的属性response.entities是一个数组:

{
    "errors": false,
    "response": {
        "entities": [
            // Entity values omitted
        ]
    },
    // Pagination omitted
}

使用此修复程序,将调用构造函数,并且您的代码基本上可以正常工作。样本fiddle

为避免将来出现此类问题,您可以使用http://json2csharp.com/Paste JSON as Classeshttps://jsonutils.com/之类的自动代码生成工具从JSON生成适当的类,然后根据需要进行修改,例如通过将自动生成的类型设为通用。