慕标5832272
您可以编写JsonConverter处理不同类型的自定义。例如,您可以使用以下 JSON:{ "Code": 0, "Msg": [ "A single string", { "Message": "An object with a message" }, { "Message": "An object with a message and a code", "Code": 5 }, { "Code": 5 } ]}在此示例中,Msg数组可以包含原始字符串或复杂对象。该对象可以包含 a Message、 aCode或两者。您将为此选择最常见的数据结构,一种能够表示所有信息的数据结构。例如,这意味着您必须将该原始字符串包装到兼容对象中。public class Error{ public int Code { get; set; } public ErrorMessage[] Msg { get; set; }}public class ErrorMessage{ public string Message { get; set; } public int? Code { get; set; }}然后您可以使用自定义然后,使用 custom JsonConverter,您可以解析上面的 JSON:public class ErrorMessageConverter : JsonConverter{ public override bool CanConvert(Type objectType) => objectType == typeof(ErrorMessage); public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // handle the primitive string if (reader.TokenType == JsonToken.String) return new ErrorMessage { Message = (string)reader.Value }; // handle a complex object; just assume that it is an `ErrorMessage` here else if (reader.TokenType == JsonToken.StartObject) return JObject.Load(reader).ToObject<ErrorMessage>(); throw new NotSupportedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); }}这将是使用该转换器的一种方法:// the single quotes are just here to make it more readable; JSON.NET support this// although it isn’t valid JSONvar json = @"{ 'Code': 0, 'Msg': [ 'A single string', { 'Message': 'An object with a message' }, { 'Message': 'An object with a message and a code', 'Code': 5 }, { 'Code': 5 } ]}";var settings = new JsonSerializerSettings()settings.Converters.Add(new ErrorMessageConverter());var result = JsonConvert.DeserializeObject<Error>(json, settings);