使用服务中的JSON数据

时间:2014-01-12 18:13:37

标签: c# json web-services visual-studio-2012 windows-8

下面的代码应该从Web服务获取数据,将其插入定义的列表“Groups”。这适用于Windows 8 metro应用程序。

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(App.DataServiceUrl + "/productcategory");
var Groups = new List<GroupList>();

if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();
    var prods = JsonConvert.DeserializeObject<dynamic>(content);
    foreach (var data in prods)
    {
        var dataGroup = new GroupList
              (
                 data.term_id,
                  data.name,
                 data.slug,
                   data.description,
                  data.taxonomy
              );
        Groups.Add(dataGroup);

    }
}

群组列表:

public class GroupList : SampleDataCommon
{


    public GroupList(String uniqueId, String title, String subtitle, String imagePath, String description)


 : base(uniqueId, title, subtitle, imagePath, description)

}

该服务数据的一个例子是:

[{"term_id":"64","name":"Argentina","slug":"argentina","term_group":"0","term_taxonomy_id":"64","taxonomy":"product_cat","description":"","parent":"13","count":"20","meta_id":"154","woocommerce_term_id":"64","meta_key":"order","meta_value":"0","cat_ID":"64","category_count":"20","category_description":"","cat_name":"Argentina","category_nicename":"argentina","category_parent":"13"},...]

但应用程序无法识别json值:

data.term_id,
data.name,
data.slug,
data.description,
data.taxonomy

相反,当我运行应用程序时,我收到此错误:

“解析值时遇到意外的字符:&lt; .Path”,第4行,第2位“

我试图从web服务json获取term_id,name等的值,并在我的应用程序中使用它。我该怎么做?我究竟做错了什么?我是否使用JSON值?

从json2csharp返回:

public class RootObject
{
    public string term_id { get; set; }
    public string name { get; set; }
    public string slug { get; set; }
    public string term_group { get; set; }
    public string term_taxonomy_id { get; set; }
    public string taxonomy { get; set; }
    public string description { get; set; }
    public string parent { get; set; }
    public string count { get; set; }
    public string meta_id { get; set; }
    public string woocommerce_term_id { get; set; }
    public string meta_key { get; set; }
    public string meta_value { get; set; }
    public string cat_ID { get; set; }
    public string category_count { get; set; }
    public string category_description { get; set; }
    public string cat_name { get; set; }
    public string category_nicename { get; set; }
    public string category_parent { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您当前正在使用不同的dataProd属性作为CategoryList的新实例的参数值。您需要决定从GroupList派生哪种类型来保存新数据,并用该类型替换CategoryList的实例化,并初始化它(通过构造函数或属性),以便新数据进入组