Michael
Michael

Reputation: 13616

Retrieve data from string type value

I have this segment code:

string responseFromServer; 
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream dataStream = response.GetResponseStream())
    {
        using (StreamReader reader = new StreamReader(dataStream))
        {
            responseFromServer = reader.ReadToEnd();
        }
    }
}

responseFromServer is a string type variable, contains this "key:value" data:

{"refresh_token":"69d2b7bq95b6sf5b64c55240ed563a52","expires_in":86400,"access_token":"0q761ee1897hd50u2r4fec80f333dd43","token_type":"bearer","x_mailru_vid":"13090076762971691053"}

This string I need to convert to this string array:

refresh_token = 69d2b7bq95b6sf5b64c55240ed563a52
expires_in = 86400
access_token = 0q761ee1897hd50u2r4fec80f333dd43
token_type = bearer
x_mailru_vid = 13090076762971691053

What is the easiest way to implement it? Thank you in advance.

Upvotes: 0

Views: 60

Answers (1)

L.B
L.B

Reputation: 116108

It is a json string. You can use any json serializer. I'll use Json.Net

var result = JsonConvert.DeserializeObject<Result>(json);  


public class Result
{
    public string refresh_token { get; set; }
    public int expires_in { get; set; }
    public string access_token { get; set; }
    public string token_type { get; set; }
    public string x_mailru_vid { get; set; }
}

You can deserialize to a dictionary too.

var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Another alternative with built-in JavaScriptSerializer

var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(json);

Upvotes: 3

Related Questions