【发布时间】:2019-05-09 12:47:56
【问题描述】:
我收到来自第 3 方的类型不明确的 API 响应。对于某些方法,它是:
{"error":{"message":"Resource is already part of this app","status_code":400}}
在其他电话上是:
{"error": "Resource is already part of this app" }
是否可以将此类响应反序列化为:
public class Response
{
[JsonProperty("error")]
public string Error { get; set; }
[JsonIgnore] //[JsonProperty("error")]
public ObjectError ObjectError { get; set; }
}
public class ObjectError
{
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("status_code")]
public string StatusCode { get; set; }
}
更新
所以我最终使用对象作为反序列化的全部。
[JsonProperty("error")]
public object Error { get; set; }
public string ErrorAsString => Error is string ? Error.ToString() : null;
public ObjectError ErrorAsObject => Error is string ? null : Error != null ? JsonConvert.DeserializeObject<ObjectError>(Error.ToString()) : null;
这并不理想,我知道。
【问题讨论】:
-
是否有不止一种类型的响应?如果没有那么也许你可以做一个
if indexOf("status_code") != -1 then ObjectError else Response -
@phuzi 你是对的,我正在更新我的问题。
标签: c# json.net deserialization json-deserialization