Search code examples
c#jsonwebrequest

Json Webrequest To C# Object


im currently developing an app which has an webrequest: I got the following class (got it from json2csharp converter):

 class InventoryJsonData
    {
        public class RootObject
        {
            public bool Success { get; set; }
            public object Error { get; set; }
            public double Price { get; set; }
            public string Username { get; set; }
        }
    }

Then i did the following coding:

ValueLoadingIndicator.IsActive = true;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(JsonBaseuri + IDInput.Text);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";

There is only one RootObject in the JSON Data. How do i get now the Price value so i can convert it into string and display it. I dont know what i need to add as c# code. If you got helpful links to JSON c# tutorials and webrequest which are about this topic and can help me to move on they are appreciated as well.


Solution

  • Take a look and Newtonsoft Json.NET library: http://www.newtonsoft.com/json

    You could also use WebClient class for you request - it's simpler to use.

    Here is example code:

    var url = JsonBaseuri + IDInput.Text;
    var wc = new WebClient {Proxy = null};
    var json = wc.DownloadString(url);
    var responseModel = JsonConvert.DeserializeObject<InventoryJsonData>(json);
    var price = responseModel.RootObject.Price;