简体   繁体   中英

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

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);

You can use the JavaScriptSerializer class:

var js = new JavaScriptSerializer();
var person = js.Deserialize<Person>(urlText);

Person, of course, should be replaced by your own .NET type. Here's also an article that might help you .

Well, one way is:

var dictionary = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(urlText);

You can use different types than a dictionary, but whether you should depends on why you're actually doing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM