[Solved] JSON.Net Seralize values don’t have quotation marks


In JSON format, numbers and booleans do not have quotes around them, while strings do (see JSON.org).

If you want quotes around all your primitives, you have a few options:

  1. Change the properties of the object you are serializing to be of type string.
  2. Put your values into a Dictionary<string, string> (or a DTO) and serialize that instead.
  3. Make a custom JsonConverter to do the conversion. This option has the advantage that it can apply globally so that you don’t have to change all your classes.

The first two options are pretty self-explanatory. If you opted to go with a converter, the code might look something like this:

class PrimitiveToStringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsPrimitive;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString().ToLower());
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To use it, simply pass an instance of the converter to the JsonConvert.SerializeObject method.

string json = JsonConvert.SerializeObject(foo, new PrimitiveToStringConverter());

Demo:

class Program
{
    static void Main(string[] args)
    {
        Foo foo = new Foo
        {
            Int = 6,
            Bool = true,
            Float = 3.14159
        };

        string json = JsonConvert.SerializeObject(foo, new PrimitiveToStringConverter());
        Console.WriteLine(json);
    }
}

class Foo
{
    public int Int { get; set; }
    public bool Bool { get; set; }
    public double Float { get; set; }
}

Output:

{"Int":"6","Bool":"true","Float":"3.14159"}

2

solved JSON.Net Seralize values don’t have quotation marks