A useful little JSON.Net wrapper for handling serialization options

Hackered
Tuesday, August 12, 2014
by Sean McAlinden

Whilst JSON.Net is clearly awesome, I have a little wrapper I have been using for years now which just abstracts a few common scenarios within my test and development code.

It is very simple to use and hopefully self explanatory:

ToJsonString

  • useCamelCase: boolean value dictates whether to create camel case keys
  • ignoreNulls: boolean value dictates whether to omit null values from the JSON structure
  • indentJson: boolean value dictates whether to indent or prettify the JSON

Example usage:

// Create an object
var user = new User { FirstName = "Sean" };
// Serialize the object to JSON
var jsonUser = JsonSerializer.ToJsonString(user, useCamelCase: true, ignoreNulls: true, indentJson: false);

FromJsonString

This method simply takes a type and string and generates an instance.

Example usage:

// Deserialize the object
var deserializedUser = JsonSerializer.FromJsonString(jsonUser); 

And here is the code:

///  /// A little wrapper for JSON.Net. /// 
public class JsonSerializer
{
    ///  /// To the json string. /// 
    ///The object to serialize.
    ///if set to true [use camel case].
    ///if set to true [ignore nulls].
    ///if set to true [indent json].
    /// 
    public static string ToJsonString(object objectToSerialize, bool useCamelCase = true, bool ignoreNulls = true, bool indentJson = false)
    {
        var settings = new JsonSerializerSettings();

        if (useCamelCase)
        {
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }

        if (ignoreNulls)
        {
            settings.NullValueHandling = NullValueHandling.Ignore;
        }

        if (indentJson)
        {
            settings.Formatting = Formatting.Indented;
        }

        return JsonConvert.SerializeObject(
            objectToSerialize,
            settings);
    } 
/// ///The json string. /// public static T FromJsonString(string jsonString) { return JsonConvert.DeserializeObject(jsonString); } }