1、反序列化匿名数组
var result = "{\"batchNum\":\"20211130042359542\",\"responseStatus\":\"SUCCESS\",\"responseMessage\":null,\"executeResult\":\"SUCCESS\",\"restResponseDtlDTOList\":[{\"documentId\":null,\"documentCode\":\"CG080120211126002\",\"responseStatus\":\"SUCCESS\",\"responseMessage\":null},{\"documentId\":null,\"documentCode\":\"CG080120211129002\",\"responseStatus\":\"SUCCESS\",\"responseMessage\":null}]}";
JObject jsonObject = result.ToJObject();
var responseList = "{\"restResponseDtlDTOList\":" + jsonObject["restResponseDtlDTOList"].ToString() + "}";
var definition = new { restResponseDtlDTOList = new[] { new { documentID = "", documentCode = "", responseStatus = "", responseMessage = "" } } };
var encryptObject = JsonConvert.DeserializeAnonymousType(responseList, definition);
var ssss = "";
foreach (var responseItem in encryptObject.restResponseDtlDTOList)
{
if (responseItem.responseStatus.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase))
continue;
ssss = "werwerwer";
}
System.Diagnostics.Debug.Write(ssss);
2、反序列化匿名对象
var definition = new { Name = "", Age = 0, Major = "" };
string json1 = @"{'Name':'GongHui','Age':28,'Major':'.NET ENGINEER'}";
var person1 = JsonConvert.DeserializeAnonymousType(json1, definition);
3、System.Text.Json的情况下:
/// <summary>
/// 反序列化为匿名对象
/// </summary>
/// <returns></returns>
[return: MaybeNull]
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject, JsonSerializerOptions? options = null)
{
return JsonSerializer.Deserialize<T>(json, options: options);
}
/// <summary>
/// 反序列化为匿名对象
/// </summary>
/// <returns></returns>
[return: MaybeNull]
public static IEnumerable<T> DeserializeListAnonymousType<T>(string json, T anonymousTypeObject, JsonSerializerOptions? options = null)
{
return JsonSerializer.Deserialize<List<T>>(json, options: options);
}