2011-05-11 56 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