使用 JSON.NET,您可以编写自定义 JSON 转换器。例如,您可以拥有以下对象:
public class Root
{
public string Status { get; set; }
public Result Result { get; set; }
}
public class Result
{
public bool? Value { get; set; }
public Item[] Items { get; set; }
}
public class Item
{
public string Name { get; set; }
public string UserIdentifier { get; set; }
public string MaxAccounts { get; set; }
}
并且您的 JSON 将被反序列化为Root[]
.
以下是自定义 JSON 转换器的外观:
public class ResultConverter: JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Result);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Boolean)
{
return new Result
{
Value = (bool)reader.Value,
};
}
return new Result
{
Items = serializer.Deserialize<Item[]>(reader),
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// If you want to support serializing you could implement this method as well
throw new NotImplementedException();
}
}
接着:
class Program
{
static void Main()
{
var json =
@"[
{
""status"": ""ok"",
""result"": true
},
{
""status"": ""ok"",
""result"": [
{
""name"": ""John Doe"",
""UserIdentifier"": ""abc"",
""MaxAccounts"": ""2""
}
]
}
]";
var settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Root[] root = JsonConvert.DeserializeObject<Root[]>(json, settings);
// do something with the results here
}
}