How to deserialize a JSON string correctly in C #?

Help to cope with proper JSON deserialization. For example, we have a JSON response to the following:

{"variant":"otvet1", "source":"otvet2", "items":[ {"list":"512"}, {"vist":"315"}, {"zist":"561"}]} 

To deserialize using the following code:

  [DataContract] public partial class ItemsList { [DataMember(Name = "list")] public string lisType { get; set; } [DataMember(Name = "vist")] public string vistType { get; set; } [DataMember(Name = "zist")] public string zistType { get; set; } } [DataContract] public partial class SourceList { [DataMember(Name = "variant")] public string variantType { get; set; } [DataMember(Name = "source")] public string vistType { get; set; } [DataMember(Name = "items")] public List <ItemsList> TestItemsList { get; set; } } public class JsonStringSerializer { public static T Deserialize<T>(string strData) where T : class { MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strData)); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); T tRet = (T)ser.ReadObject(ms); ms.Close(); return (tRet); } } private static SourceList SourceTempList; SourceTempList = JsonStringSerializer.Deserialize<SourceList>(e.Result); //in e.Result JSON response 

In the previous code, it works, but if you change the JSON response, it does not work ... New JSON answer:

 {"variant":"otvet1", "source":"otvet2", "items":[3, {"list":"512"}, {"vist":"315"}, {"zist":"561"}]} 

In this case, the C # code for deserialization does not work ... There are elements in number 3, tell me how to deserialize the JSON response to this? A list of vist and zist were available ... Help me ... please

+4
source share
1 answer

Historically, a DataContractJsonSerializer was seen as broken. The recommendation is to use JSON.Net http://james.newtonking.com/projects/json-net.aspx

Check for deserialization issue with DataContractJsonSerializer

+4
source

All Articles