Alan Alan - 2 months ago 5
ASP.NET (C#) Question

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

On my server I tried this test code:

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("");
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?


You need to deserialize the JSON to C# objects.

These links will help you:

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.