2011-09-26 62 views
4

幫助處理JSON反序列化的正確答案。例如,我們有JSON迴應如下:如何反序列化JSON字符串在C#中是正確的?

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

反序列化使用下面的代碼:

[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 

在上面的代碼,它的工作原理,但如果你改變了JSON響應,它不行...... 新的JSON響應:

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

在這種情況下,反序列化的C#代碼不會出現3個數工作... 項目,告訴我如何反序列化對此的JSON響應? 可用於列表vist和zist ...幫助我...請

+1

我總是用牛頓軟件json.net – pm100

回答

相關問題