简体   繁体   中英

Decoding (JSON) HttpWebResponse in C#

Here is my code:

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var vrati = Newtonsoft.Json.JsonConvert.DeserializeObjectAsync(responseString);
log.Text = vrati["f"][0];

I'm using Newtonsoft .Json.JsonConvert and I don't know how to go.

JSON Code is like

{"a":13,"o":215,"f":["g","i"]}

And I want to get ["f"][0] .. "g" in my sample. Please help me.

Try this, using dynamics

string responseString = "{\"a\":13,\"o\":215,\"f\":[\"g\",\"i\"]}";
dynamic vrati = JObject.Parse(responseString);

log.Text = vrati["f"][0];

You can parse it into a dynamic object:

string data = "{\"a\":13,\"o\":215,\"f\":[\"g\",\"i\"]}";
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(data);
string result = obj.f[0].Value;

If you want something dynamic, quick and dirty you could just:

var dynJson = JsonConvert.DeserializeObject<dynamic>("{\"a\":13,\"o\":215,\"f\":[\"g\",\"i\"]}");

    Console.WriteLine(dynJson.a);
    Console.WriteLine(dynJson.o);

    foreach(var something in dynJson.f){
        Console.WriteLine(something);
    }

If you want something typed you can create an object that matches your Json and Deserialize:

    void Main()
{
    var dynJson = JsonConvert.DeserializeObject<MyThing>("{\"a\":13,\"o\":215,\"f\":[\"g\",\"i\"]}");

    Console.WriteLine(dynJson.a);
    Console.WriteLine(dynJson.o);
    foreach(var something in dynJson.f){
        Console.WriteLine(something);
    }
}

public class MyThing {

    public int a {get;set;}
    public int o {get;set;}
    public List<string> f {get;set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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