简体   繁体   English

如何在C#中反序列化JSON字符串是正确的?

[英]How to deserialize JSON string is correct in c#?

Help to deal with JSON deserialization correct answer. 帮助处理JSON反序列化正确答案。 For example, we have JSON response to the following: 例如,我们对以下内容进行了JSON响应:

{"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: 在前面的代码中,它可以工作,但是如果你更改了JSON响应,它就不起作用......新的JSON响应:

{"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? 在这种情况下,用于反序列化的c#代码不起作用...出现了数字3中的项目,告诉我如何反序列化对此的JSON响应? Were available to list vist and zist ...Help me...please 可以列出vist和zist ...请帮帮我......

Historically the DataContractJsonSerializer has been seen as broken. 历史上,DataContractJsonSerializer被视为已损坏。 The reccomendation is to use JSON.Net http://james.newtonking.com/projects/json-net.aspx 推荐使用JSON.Net http://james.newtonking.com/projects/json-net.aspx

Check out Deserialization problem with DataContractJsonSerializer 查看DataContractJsonSerializer的反序列化问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM