Search code examples
c#.netwindowswindows-phone-8windows-store-apps

How to parse JSON in Windows Store / Windows Phone App


The url that I have returns follwing JSON

[{"Id":21,"Name":"Pop","Description":"Pop Music"},{"Id":22,"Name":"Classical","Description":"Classical Music"},{"Id":23,"Name":"Rock","Description":"Rock Music"}]

and I want to populate List<Genre> genreList; where Genre looks like

class Genre
{
  int Id{get;set;}
  string Pop{get;Set;}
  string Description {get;set;}
}

I wrote following code but it is not at all working

public List<Genre> GetAllGenres()
        {
            var client = new HttpClient();
            HttpResponseMessage response =  client.G(new Uri("http://localhost/MusicAPI/api/Genre/GetAllGenres/"));
            var jsonString =  response.Content.ReadAsString();

            List<Genre> list = await Newtonsoft.Json.JsonConvert.DeserializeObject<Genre[]>(jsonString);
            return list;
        }

Please suggest..

Here is the answer given by Jagath

 public GenreItemViewer()
        {
            this.InitializeComponent();
            GetResponse();
        }

        public async void GetResponse()
        {
            var postRequest = (HttpWebRequest)WebRequest.Create("http://localhost/MusicAPI/api/Genre/GetAllGenres/");
            postRequest.Method = "GET";
            postRequest.CookieContainer = new CookieContainer(); ;

            HttpWebResponse postResponse = (HttpWebResponse)await postRequest.GetResponseAsync();
            string response = String.Empty;
            if (postResponse != null)
            {
                var postResponseStream = postResponse.GetResponseStream();
                var postStreamReader = new StreamReader(postResponseStream);

                response = await postStreamReader.ReadToEndAsync();
            }

            List<Genre> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Genre>>(response);
        }

Solution

  • Try

    List<Genre> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Genre>>(jsonString);
    

    For Getting the Http response

    var postRequest = (HttpWebRequest)WebRequest.Create(url);               
    postRequest.Method = "GET";                
    postRequest.CookieContainer = new CookieContainer();;
    
    HttpWebResponse postResponse = (HttpWebResponse)await postRequest.GetResponseAsync();
    
    if (postResponse != null)
    {
       var postResponseStream = postResponse.GetResponseStream();
       var postStreamReader = new StreamReader(postResponseStream);
    
       string response = await postStreamReader.ReadToEndAsync();
        return response;// This is the response
    }