I am a newbie in asp.net MVC. I want to create a plain c# client program that consumes json returned from a asp.net mvc progam. What is the best method for retrieving the json data from the asp.net MVC site? I currently use WebRequst, WebResponse and StreamReader to retrieve the data. Is this a good method, otherwise what is the best practice to get the data? Can I use something like below? Thanks a lot
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string urlText = reader.ReadToEnd();
//Then parse the urlText to json object
You don't parse the text to JSON object on server side because JSON is Javascript Object Notation and C# knows nothing about that. You parse the JSON string to a specific type. For example:
string json = {"Name":"John Smith","Age":34};
Can be deserialized to a C# class Person as so:
public class Person
{
public string Name {get;set;}
public int Age {get;set;}
}
JavascriptSerializer js= new JavascriptSerializer();
Person john=js.Desearialize<Person>(json);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With