4

Help to deal with JSON deserialization correct answer. For example, we have 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 response:

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

In this case, c # code for deserialization does not work ... Items in the number 3 appeared, tell me how to deserialize the JSON response to this? Were available to list vist and zist ...Help me...please

arsenium
  • 571
  • 1
  • 7
  • 20

1 Answers1

4

Historically the DataContractJsonSerializer has been seen as broken. The reccomendation is to use JSON.Net http://james.newtonking.com/projects/json-net.aspx

Check out Deserialization problem with DataContractJsonSerializer

Community
  • 1
  • 1
Dave Walker
  • 3,498
  • 1
  • 24
  • 25