c# - 反序列化为具有私有字段的对象
问题描述
我正在为 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);
我怎样才能以正确的方式做到这一点?
解决方案
添加JsonPropertyAttribute将指示 json.net 反序列化到私有字段。
IE
public class ErrorResponse
{
[JsonProperty("errors")]
private readonly IDictionary<string, IList<Error>> _errors;
public ErrorResponse()
{
_errors = new Dictionary<string, IList<Error>>();
}
//...
}
推荐阅读
- android - 改造 2 不适用于 android api 级别 17
- vue.js - 垂直滚动时更新 vuetify 导航抽屉中的选定项目
- java - 如何在弹出的模式中单击确认按钮
- mongodb - Microsoft Cosmosdb for Mongodb:将未分片的集合合并到分片的集合中
- excel - 如何使循环从另一张表中提取值?
- http - 我无法让我的子路由器正常工作
- javascript - 如何使用 if/else 语句编写 javascript 函数来检查是否存在类包含一个或类
- reactjs - 在 React 组件中的多个 GraphQL 查询之间进行更改
- java - JPQL 和实体数据
- react-native - 反应本机:从手机发送数据到另一个没有互联网的手机