如何从json格式化的字符串访问子项,子子项及其子项

时间:2015-07-18 09:35:56

标签: c#

这是API链接。 https://api.indix.com/v2/offersPremium/products?countryCode=US&q=macys&name=10168--Electronics&app_id=dbffc3ab&app_key=6c1608f7ba90259040aa98132f29b433

和我从这个API链接获取mpns,upcs,maxSalePrice的值。我以这种格式获取值

foreach (JToken child in result.Children())
{
    foreach (JToken grandChild in child)
    {
        foreach (JToken grandGrandChild in grandChild)
        {
            var upsc = System.Convert.ChangeType(result["upcs"].ToString(), type);
            var MPN = System.Convert.ChangeType(result["mpns"].ToString(), type);
            var maxSalePrice = System.Convert.ChangeType(result["maxSalePrice"].ToString(), type);
        }
    }
}

但这只给出了一次值,我从API链接获得了这些对象的所有值。

1 个答案:

答案 0 :(得分:0)

您需要将result["upcs"]等替换为grandGrandChild["upcs"]

string url = "https://api.indix.com/v2/offersPremium/products?countryCode=US&q=macys&name=10168--Electronics&app_id=dbffc3ab&app_key=6c1608f7ba90259040aa98132f29b433";
var type = typeof(string);

WebClient wc = new WebClient();
JObject results = JsonConvert.DeserializeObject<JObject>(wc.DownloadString(url));

foreach (var result in results["result"]["products"])
{
    string CatId = (string)result["categoryId"];
    string catname = ddlRetailerName.SelectedItem.Text;
    JToken fetchrecord = ddlcategories.SelectedItem.Text;
    string title = (string)result["title"];
    int brandid = (int)result["brandId"];
    string brandname = (string)result["brandName"];
    var upsc = Convert.ChangeType(result["upcs"].ToString(), type);
    var MPN = Convert.ChangeType(result["mpns"].ToString(), type);
    var maxSalePrice = Convert.ChangeType(result["maxSalePrice"].ToString(), type);
}