2011-05-11 99 views
1

我有這樣的JSON字符串Windows Phone 7的JSON解析錯誤

{ "rs:data": { "z:row": [ {"Lead": "", "Industry": "Other Commercial", "ID": "908", "Name": "3PAR Ltd." }, {"Lead": "Ebeling, Kevin R.", "Industry": "Retail", "ID": "1", "Name": "7-Eleven" } ] }} 

現在我在上面的格式從Web服務將數據傳輸到贏手機7. 但是當試圖解析我面臨的一個錯誤:

void fetcher_GetClientsCompleted(object sender, ServiceReference2.GetClientsCompletedEventArgs e) 
    { 
     StringReader reader; 
     reader = new StringReader(e.Result); 
     IList<Clientclass> cc; 
     string MyJsonString = reader.ReadToEnd(); // 

     cc = Deserialize(MyJsonString); 
    } 


    public static IList<Clientclass> Deserialize(string json) 
    { 
     using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) 
     { 
      var serializer = new DataContractJsonSerializer(typeof(IList<Clientclass>)); 
      return (IList<Clientclass>)serializer.ReadObject(ms); 
     } 
    } 

我的數據必須解析爲每clientclass,其中clientclass是:

public class Clientclass 
    { 
     string _id; 
     string _name; 
     string _industry; 
     string _lead; 

     public string ID 
     { 
      get { return _id; } 
      set { _id = value; } 
     } 
     public string Name 
     { 
      get { return _name; } 
      set { _name = value; } 
     } 
     public string Industry 
     { 
      get {return _industry; } 
      set { _industry= value; } 
     } 
     public string Lead 
     { 
      get { return _lead; } 
      set { _lead = value; } 
     } 
    } 

請注意JSON字符串中有多個記錄。

感謝 santu

+5

和錯誤是...? – 2011-05-11 12:33:53

回答

1

你反序列化錯誤的類型(IList的,而不是ClientClass的列表 - original post had typeof(IList)但是克里斯糾正了這個作爲自己的代碼格式編輯的一部分)。你應該這樣做:

public static List<Clientclass> Deserialize(string json) 
{ 
    using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) 
    { 
     var serializer = new DataContractJsonSerializer(typeof(List<Clientclass>)); 
     return (List<Clientclass>)serializer.ReadObject(ms); 
    } 
} 

此外,你的JSON包括你沒有解碼的東西。如果你想用上面的方法,你的JSON必須是:

[ {"Lead": "", "Industry": "Other Commercial", "ID": "908", "Name": "3PAR Ltd." }, {"Lead": "Ebeling, Kevin R.", "Industry": "Retail", "ID": "1", "Name": "7-Eleven" } ] 

爲了將字符串從您的原始信息進行解碼,你需要一個包含類,並定義DataMember屬性來處理名稱:

public class ClassA 
    { 
     [DataMember(Name = "rs:data")] 
     public ClassB Data { get; set; } 
    } 

    public class ClassB 
    { 
     [DataMember(Name="z:row")] 
     public List<Clientclass> Row { get; set; } 
    } 

然後反序列化ClassA的:

public static ClassA Deserialize(string json) 
    { 
     using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) 
     { 
      var serializer = new DataContractJsonSerializer(typeof(ClassA)); 
      return (ClassA)serializer.ReadObject(ms); 
     } 
    } 
+0

這個json不能代表一個字典>帶有一個項目,name ='z:row'和一個List ? – AwkwardCoder 2011-05-11 16:35:05