使用不同的模式反序列化 JSON

我将 JSON.Net 与 .NET 4.7 一起使用。


在我调用的 API 中,对于同一个调用,我似乎可以随机获得两种错误 json :(。


错误类型 1:


{

   "Code": 0,

   "Msg": ["Some Warning"]

}

错误类型 2:


{

    "Code": 0,

    "Msg": [

          {"Error": 5 },

          {"Error": 6 }

    ]

}

正如你所看到的,它Msg改变了它的结构。我想要一个通用的 POCO 来反序列化,但是什么时候Msg改变呢?


JsonConvert.DeserializeObject<MyCommonPoco>(theJson);


翻翻过去那场雪
浏览 188回答 1
1回答

慕标5832272

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