在C#RootObject中反序列化父JSON数据

时间:2014-01-05 23:08:50

标签: c# json-deserialization

有人可以帮我弄清楚如何使用此示例代码在C#中获取JSON数据中的父数据吗?

 string JSON = JsonConvert.SerializeObject(message["data"]);
                //Deserialize to strongly typed class i.e., RootObject
                RootObject obj = JsonConvert.DeserializeObject<RootObject>(JSON);

                //loop through the list and show on console
                foreach (Result resultsItem in obj.results)
                {
                    Console.WriteLine(resultsItem.shipping + "-" + resultsItem.model + "-" + resultsItem.price +
                           "-" + resultsItem.product_name);

                }

和root对象类看起来像这样

public class Result
{
    public string shipping { get; set; }
    public string model { get; set; }
    public string price { get; set; }
    public string item { get; set; }
    public string product_name { get; set; }
    public string availability { get; set; }
}

public class RootObject
{
    public List<object> cookies { get; set; }
    public List<Result> results { get; set; }
    public string connectorGuid { get; set; }
    public string connectorVersionGuid { get; set; }
    public string pageUrl { get; set; }
    public int offset { get; set; }
}

我能够在Result类中编写显示列的代码,但我不知道如何在rootobject类中访问“PageUrl”。我在foreach循环中尝试了所有可能的名称,但RootObject中的列无法访问。任何帮助将不胜感激。 感谢

1 个答案:

答案 0 :(得分:1)

这就是你需要的吗?

foreach (Result resultsItem in obj.results)
{
    Console.WriteLine(resultsItem.shipping 
                      + "-" + resultsItem.model 
                      + "-" + resultsItem.price 
                      + "-" + resultsItem.product_name 
                      + "-" + obj.pageUrl);

}

此代码将为每行结果显示pageUrl