0

这是我的 json 字符串中的 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/pi:

    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 反序列化上述字符串。试过在网上找资源,没用。我的列表框未填充源并显示为空。

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

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
4

1 回答 1

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
    }

所有工作都很棒。问候

于 2013-04-23T08:58:30.173 回答