简体   繁体   English

如何从我的响应httpwebreponse中读取json响应

[英]how to read the json response from my response httpwebreponse

This is my sample string 这是我的示例字符串

{
"aaa": "0",
"nnn": "Ok",
"rrr": [
    {
        "id": "0",
        "name": "Reserved",
        "desc": "Reserved",
        "shortdesc": "",
        "price": "07.80",
        "isvariableprice": "0",
        "taxcategoryid": "0",
        "istaxinclusive": "0",
        "brandid": "1",
        "isnetsalesexempt": "0",
        "itemtype": "0",
        "skus": [],
        "modifiergroups": [],
        "prices": [],
        "pricerules": [],
        "categories": [],
        "nutrition": [
            {
                "id": "1",
                "amount": "10.0000"
            }
        ]
    }
    ]
}

I want to only retrieve "id" and "price" from the sample json response. 我只想从示例json响应中检索“ id”和“ price”。 The JSON is more that this and have multiple id;s and prices ... how do I put a loop to retrieve all those in an array. JSON不仅具有此功能,而且具有多个ID; S和价格...我该如何放置循环以检索数组中的所有ID。 Please help. 请帮忙。

This is where I am right now. 这就是我现在的位置。

if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream receiveStream = response.GetResponseStream();
                    StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                    Console.WriteLine("Response stream received.");

                    string resultString = readStream.ReadToEnd();
                    //var ser = new DataContractJsonSerializer(typeof(RootObject));

                    var stream = new MemoryStream(Encoding.Unicode.GetBytes(resultString));
                    dynamic data = JsonObject.Parse(resultString);

                    Console.WriteLine(data.id); //??????????

                    readStream.Close();
                }

this code gives me above string in "data" but I want to pull "id" and "price" 该代码使我在“数据”中的字符串上方,但我想提取“ id”和“ price”

thx in advance all you gurus 预先感谢所有大师

Json.Net will make your life easier when working with JSON http://json.codeplex.com/ 使用JSON http://json.codeplex.com/时,Json.Net将使您的生活更轻松

With Json.Net in place. 有了Json.Net。

You can do this in a dynamic fashion or in a strongly typed fashion. 您可以动态方式或强类型方式执行此操作。

dynamic: 动态:

var dynJson = JsonConvert.DeserializeObject<dynamic>(yourJsonString);

    //for simple values
    Console.WriteLine(dynJson.aaa);
    Console.WriteLine(dynJson.nnn);

    //for list values
    foreach(var r in dynJson.rrr){
        //for simple values in rrr
        Console.WriteLine(r.id);

        //for list values in rrr
        foreach(var price in rrr.prices)
          Console.WriteLine(price)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM