我有两个具有“ resultObject”属性的json响应。其中一个返回对象,另一个返回字符串/布尔值。
我有一个用于JSON的C#对象。
public class UseInboxResult
{
public string version { get; set; }
public bool resultStatus { get; set; }
public int resultCode { get; set; }
public string resultMessage { get; set; }
public ResultObject resultObject { get; set; }
}
public class ResultObject
{
public string access_token { get; set; }
public int expires_in { get; set; }
public string token_type { get; set; }
public int displayCount { get; set; }
public int totalCount { get; set; }
public List<Items> items { get; set; }
}
JSON对象具有不同类型的resultObject属性
//First
{
"version": "1.0.0",
"resultStatus": true,
"resultCode": 200,
"resultMessage": "Your operation has been completed successfully.",
"resultObject": {
"displayCount": 1,
"totalCount": 1,
"items": [
{
"id": "5db72eec92b565000100a0aa",
"createTime": "2019-10-28T18:09:48.924Z",
"updateTime": "2019-12-20T18:10:41.451Z",
"displayName": "John Doe",
"email": "john.doe@example.com",
"activation": true,
"notifyDedicatedIps": null
}
]
}
}
//Second
{
"version": "1.0.0",
"resultStatus": false,
"resultCode": 200,
"resultMessage": "OK",
"resultObject": "5e0491bdaf6d250001834b75"
}
如何为此属性绑定c#类。
答案 0 :(得分:1)
您可以将ResultObject
替换为object
,然后检查resultStatus
如果resultStatus == true
将resultObject
反序列化为ResultObject
。
否则将resultObject
反序列化为string
public class UseInboxResult
{
public string version { get; set; }
public bool resultStatus { get; set; }
public int resultCode { get; set; }
public string resultMessage { get; set; }
public object resultObject { get; set; }//<--NOTE THIS
}
var data = JsonConvert.DeserializeObject<UseInboxResult>(json);
//var data = System.Text.Json.JsonSerializer.Deserialize<UseInboxResult>(json); .Net Core 3
if (data.resultStatus == true)
{
ResultObject result = JsonConvert.DeserializeObject<ResultObject>(data.resultObject.ToString());
}
else
{
string result = JsonConvert.DeserializeObject<ResultObject>(data.resultObject.ToString());
}
答案 1 :(得分:1)
您可以使用泛型将它们拆分为单独的部分。
public class Response<T>
where T : class
{
public string version { get; set; }
public bool resultStatus { get; set; }
public int resultCode { get; set; }
public T resultMessage { get; set; }
}
public class ResultObject
{
// Your same ResultObject.
}
您现在可以根据要呼叫的内容反序列化为Response<ResultObject>
或Response<string>
。