我正在为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);
我该怎么做呢?