Im trying to parse a http web response into an array or something so i can work with the information. This is the json response i get (+ a lot more, but i just censored the format):
{
"meta": {
"status": 200
},
"data": {
"account": {
"account_phone_number": "XXXXXXXX",
"account_email": "[email protected]"
},
"user": {
"id": "5f2b17e7836fc7010025aed3",
"age": 23,
}
}
}
How can i write the "id" inside of "user" to console or a textbox?
This is my web request:
private void button1_Click(object sender, EventArgs e)
{
const string WEBSERVICE_URL = "url_here";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 12000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("x-auth-token", "Auth_token");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
richTextBox1.AppendText(jsonResponse);
}
}
}
}
catch (Exception ex)
{
richTextBox1.AppendText("No workie");
}
}
I have tried the following:
public class Test
{
public string meta {get;set;}
public string data {get;set;}
}
and trying to serialize the json into a table as following:
JavaScriptSerializer js = new JavaScriptSerializer();
Test[] Tester = js.Deserialize<Test[]>(jsonResponse);
richTextBox1.AppendText(Tester);
But no luck. Can anyone please point me in the right direction here?
If you are able to use other serializer than
JavaScriptSerializerthen you can take advantage of partial deserializing.In case of Json.NET (formerly known as Newtonsoft Json) you have at least two options:
SelectTokenParsemethod we will have a semi-parsed object.SelectTokenreturns aJToken. From it you can retrieve data in several ways:(string)semiParsedData.SelectToken("data.user.id")semiParsedData.SelectToken("data.user.id").Value<string>()semiParsedData.SelectToken("data.user.id").ToObject<string>()References:
indexer operatorJTokendefines the following indexer operator, which is not really useful:JObjectoverrides this to make that functionality useful:JObjectderives fromJContainer, which derives fromJToken).Propertymethod tries to get the requested entity from the_propertiescollection:private readonly JPropertyKeyedCollection _propertiesReference: