Nuget Package: Json.NET

Json.NET is a must have nuget package when you are working with web APIs. And it can be pretty handy in many other cases as well.

The documentation includes over a hundred examples on how to use it.

It can be used to easily Clone objects by serializing and deserializing:

public static T Clone<T>(this T source)
{
    if (Object.ReferenceEquals(source, null))
    {
        return default(T);
    }

    return JsonConvert.DeserializeObject<T>(
        JsonConvert.SerializeObject(source)
    );
}

Json.NET can handle “a wide variety of .NET objects”, it serializes the information required to revert it back later.

It is possible to map a property to a name but adding the attribute JsonPropertyAttribute:

public class Game
{
    public int ID { get; set; }

    public string Name { get; set; }

    [JsonProperty(propertyName: "price_value")]
    public decimal Price { get; set; }
}

When serialized generates:

{"ID":1,"Name":"Breath of Fire IV","price_value":1337.00}

Json can be parsed in a dynamic object:

public static void DynamicJsonExample()
{
    var editGameViewModel = new EditGameViewModel
    {
        Name = "Breath of Fire IV",
        Price = 1337.00M,
    };

    var json = JsonConvert.SerializeObject(editGameViewModel);

    dynamic jsonObj = JsonConvert.DeserializeObject(json);

    string name = jsonObj.Name; // Breath of Fire IV
    decimal price = jsonObj.Price; // 1337
    string expt = jsonObj.NotSerializedThingIsNull; // null
}

Json.NET on Stack Overflow

Advertisements

One thought on “Nuget Package: Json.NET

  1. Pingback: An overview of Extension Methods and a handful set of them | Coding Wise

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s