How to convert a JSON response to a C# object?

Question:

I'm making a request and getting a JSON like this:

{
  "id": "1000000000000000", 
  "name": "BrunoLM", 
  "first_name": "Bruno", 
  "last_name": "X", 
  "link": "http://stackoverflow.com/users/340760/brunolm", 
  "username": "brunolm", 
  "bio": "...",
  "gender": "male", 
  "timezone": -2, 
  "locale": "en_US"
}

But the server doesn't always send all these fields, sometimes it can come without locale , or link

I would like to convert this to an object and be able to access it by properties:

objeto.name      // ou objeto.Name
objeto.last_name // ou objeto.LastName

How to do this? What is most recommended?

If the most recommended option is to use a library, there is a question of curiosity: is it possible to do it using only what .NET offers?

Answer:

I recommend using Json.NET

See the Documentation example

Product product = new Product();

product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
Scroll to Top