3

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
3
  • My question is if it is ok to use WebRequst, WebResponse and StreamReader to get json data from a asp.net MVC program. Thanks Commented Oct 28, 2011 at 14:44
  • Without using WCF, then WebRequest would fine and is in fact the only option available to you. Commented Oct 28, 2011 at 15:17
  • As Simon stated its pretty much your only option. You could look at the newer wcf web api classes such as HttpClient that may make a little more sense to you. nuget.org/List/Packages/WebApi.All Commented Oct 28, 2011 at 17:11

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

That's what I am looking for. But Part of my question is if it is ok to use WebRequst, WebResponse and StreamReader to get json data from a asp.net MVC program or there is some other practice. Thanks for your time
@user394128 I don't see why not. The bottom line is that if you get get a json string on your http response you should be able to construct your objects from that json string using the Javascript Serializer.
3

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.