首页 > 解决方案 > 反序列化为具有私有字段的对象

问题描述

我正在为 Web API 开发 SDK。我使用 httpClient 对端点进行 http 调用,如果出现一些错误,我会收到以下响应,状态码为 400

{
    "errors": {
        "InstanceId": [
            {
                "code": "GreaterThanValidator",
                "message": "'InstanceId' must be greater than '0'."
            }
        ],
        "Surcharges[0]": [
            {
                "code": null,
                "message": "Surcharge Name is invalid. It should not be empty."
            }
        ]
    }
}

在我的应用程序(SDK)中,我的类应该包含一组分组错误。

 public class ErrorResponse
    {
        private readonly IDictionary<string, IList<Error>> _errors;

        public ErrorResponse()
        {
            _errors = new Dictionary<string, IList<Error>>();
        }

        public ErrorResponse(string propertyName, string code, string message)
            : this()
        {
            AddError(propertyName, code, message);
        }

        public IReadOnlyDictionary<string, IList<Error>> Errors =>
            new ReadOnlyDictionary<string, IList<Error>>(_errors);

        public void AddError(string propertyName, string code, string message)
        {
            if (_errors.ContainsKey(propertyName))
            {
                _errors[propertyName].Add(new Error(code, message));
            }
            else
            {
                _errors.Add(propertyName, new List<Error> { new Error(code, message) });
            }
        }
    }

如何将该 json 反序列化为ErrorResponse类?我试过了,但错误总是空的:

string content = await responseMessage.Content.ReadAsStringAsync();
var validationErrors = JsonConvert.DeserializeObject<ErrorResponse>(content);

我怎样才能以正确的方式做到这一点?

标签: c#json.netjson-deserialization

解决方案


添加JsonPropertyAttribute将指示 json.net 反序列化到私有字段。

IE

public class ErrorResponse
{
    [JsonProperty("errors")]
    private readonly IDictionary<string, IList<Error>> _errors;

    public ErrorResponse()
    {
        _errors = new Dictionary<string, IList<Error>>();
    }

    //...
}

推荐阅读