Alan2
Alan2

Reputation: 24562

How can I convert a ASP.NET WebAPI calls that returns JSON into a list?

On my server I tried this test code:

    [AllowAnonymous]
    [Route("GetX")]
    public IQueryable<Phrase> GetX()
    {
        var phrases = new List<PhraseX>
        {
            new PhraseX() {Keyword="abc", Translation1="abc1", Translation2="abc2" },
            new PhraseX() {Keyword="def", Translation1="def1", Translation2="def2" },
            new PhraseX() {Keyword="ghi", Translation1="ghi1", Translation2="ghi2" },

        };
        return db.Phrases;
    }

Here's what I have so far on the client which is a terminal application:

var request = HttpWebRequest.Create("http://www.example.com/api/Phrase/GetX");
        request.ContentType = "application/json";
        request.Method = "GET";

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {

I am getting the expected data back but now I am not sure how can I get the data that's returned as json back into a list? Any suggestions on how I could do this?

Upvotes: 0

Views: 66

Answers (2)

trashr0x
trashr0x

Reputation: 6565

You can deserialize the JSON to C# objects, as stated in the previous answer.

Using Json.NET (Newtonsoft.Json namespace), you can pass your JSON data to the JsonConvert.DeserializeObject<T>(json_data) method, with T being the data type the JSON should be deserialized into and json_data obviously being the JSON data you have received. You can obviously also use the built-in JavaScriptSerializer if you don't want to introduce a third-party dependency to your solution.

Visual Studio gives you a very easy way to create the C# classes for your JSON, have a look at my answers here and here.

Upvotes: 0

Saurabh R S
Saurabh R S

Reputation: 3177

You need to deserialize the JSON to C# objects.

These links will help you:
https://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx http://www.newtonsoft.com/json/help/html/deserializeobject.htm

This is how you may do it:

string jsonStr = "[{Keyword:\"abc\", Translation1:\"abc1\", Translation2:\"abc2\" },{Keyword:\"def\", Translation1:\"def1\", Translation2:\"def2\" },{Keyword:\"ghi\", Translation1:\"ghi1\", Translation2:\"ghi2\" }]";

JavaScriptSerializer jss = new JavaScriptSerializer();
List<PhraseX> phrases = jss.Deserialize<List<PhraseX>>(jsonStr);  

where PhraseX is a class-

public class PhraseX
{
    public string Keyword { get; set; }
    public string Translation1 { get; set; }
    public string Translation2 { get; set; }
}  

Note: You will find JavaScriptSerializer class in System.Web.Extensions.dll
You may also use JSON.NET for same.

Hope it helps.

Upvotes: 2

Related Questions