Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get JSON data in a plain c# program from a ASP.net MVC program?

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
like image 365
c830 Avatar asked Dec 21 '25 05:12

c830


1 Answers

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);
like image 128
Icarus Avatar answered Dec 22 '25 20:12

Icarus