Barış Kısır

Software Developer at Accenture

Navigation
 » Home
 » About
 » Resume
 » Projects
 » Contact
 » RSS

Deserialize Json with Newtonsoft

25 Oct 2016 » csharp

Creating class for json value

I use this public api for testing http://jsonplaceholder.typicode.com/posts

public class RootObject
        {
            public int userId { get; set; }
            public int id { get; set; }
            public string title { get; set; }
            public string body { get; set; }
        }

There is also auto-generate tool for that Json2Csharp

(19.05.2017) Update: With VS2017 you can paste json/xml as classes. VS 2017 Paste Special

Solution

HttpClient httpclient = new HttpClient();
HttpResponseMessage httpResponseMessage = httpclient.GetAsync("http://jsonplaceholder.typicode.com/posts").Result;
var responseContent = httpResponseMessage.Content;
string json = responseContent.ReadAsStringAsync().Result;
List<RootObject> rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RootObject>>(json);
        foreach (var item in rootObject)
        {
                Console.Write(item.title);
        }