无法使用Json数据填充列表框

时间:2013-04-23 07:55:49

标签: json windows-phone-7 c#-4.0

这是我在json string中的C#类:

public class Products

        {
            public string cid { get; set; }
            public string name { get; set; }

        }

        public class RootObject
        {
            public List <Products> product  { get;set; }
            public int success { get; set; }
        }

C#代码:

void myButton_Click(object sender,RoutedEventArgs e)
        {

          WebClient wc = new WebClient();
          wc.DownloadStringAsync(new Uri("http://ensignweb.com/sandbox/app/comment11.php"));
          wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {

       string  MyJsonString = e.Result;
       var jsonObj = JObject.Parse(MyJsonString);



   Products products = JsonConvert.DeserializeObject<Products>(jsonObj.ToString());
   TestList.ItemsSource = products.name;

}

调试时得到的O / p:

    string jsonObj= {
      "products": [
        {
          "cid": "1",
          "name": "bernard"
        },
        {
          "cid": "2",
          "name": "Vijay"
        },
        {
          "cid": "3",
          "name": "vikas_admin"
        },
        {
          "cid": "4",
          "name": "vikas_admin"
        },
        {
          "cid": "5",
          "name": "vikas_admin"
        },

      ],
      "success": 1
    }   

products:TestApp.TestNews.Products

请帮助使用Json.net反序列化上面的字符串。试图在网上寻找资源,没用。我的列表框没有填充源并显示为null。

更新: 尝试建议的代码后得到o / p:

TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product
TestApp.TestNews+Product

1 个答案:

答案 0 :(得分:0)

好的,请使用此

[DataContract]
public class Products
{
    [DataMember (Name = "cid")]
    public string Cid { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }
}

[DataContract]
public class RootObject
{
     [DataMember(Name = "products")]
    public List<Products> ProductList { get; set; }
}

  private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        var json = e.Result;
        var products = JsonConvert.DeserializeObject<RootObject>(json);
        TestList.ItemsSource = products.ProductList; // this line was updated
    }

所有工作都很好。此致