反序列化为具有私有字段的对象
Deserialization to object with private field
我正在为 Web 开发 SDK API。我使用 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) 中,我有 class 应该包含一组错误分组。
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
class?我已经试过了,但错误总是空的:
string content = await responseMessage.Content.ReadAsStringAsync();
var validationErrors = JsonConvert.DeserializeObject<ErrorResponse>(content);
我怎样才能以正确的方式做到这一点?
添加 JsonPropertyAttribute 将指示 json.net 反序列化到私有字段。
I.E.
public class ErrorResponse
{
[JsonProperty("errors")]
private readonly IDictionary<string, IList<Error>> _errors;
public ErrorResponse()
{
_errors = new Dictionary<string, IList<Error>>();
}
//...
}
我正在为 Web 开发 SDK API。我使用 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) 中,我有 class 应该包含一组错误分组。
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
class?我已经试过了,但错误总是空的:
string content = await responseMessage.Content.ReadAsStringAsync();
var validationErrors = JsonConvert.DeserializeObject<ErrorResponse>(content);
我怎样才能以正确的方式做到这一点?
添加 JsonPropertyAttribute 将指示 json.net 反序列化到私有字段。
I.E.
public class ErrorResponse
{
[JsonProperty("errors")]
private readonly IDictionary<string, IList<Error>> _errors;
public ErrorResponse()
{
_errors = new Dictionary<string, IList<Error>>();
}
//...
}