41

When calling Newtonsoft.Json.JsonConvert.SerializeObject(myObject) I'm getting keys and values enclosed in double quotes like this:

{"key" : "value"}

I would like them to be enclosed in single-quotes like this:

{'key' : 'value'}

Is it possible to do using Json.Net?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
rony l
  • 5,798
  • 5
  • 35
  • 56
  • This seems to be a question already asked. http://stackoverflow.com/questions/13541998/how-to-encode-the-single-quote-apostrophe-in-json-net . Refer to that question to see if it helps you out. – Bearcat9425 Feb 04 '15 at 15:37
  • 2
    not really a pretty thing, but it works: `json.Replace("\"", "\'");` – stefankmitph Feb 04 '15 at 15:38
  • I think that you can achieve your goal using a solution similar to the one used on this [answer](http://stackoverflow.com/a/9280598/982431). The solution will pass from create a custom `JsonConverter` class that writes raw values and surround it with single quotes. – HuorSwords Feb 04 '15 at 15:40
  • 2
    In 2018, you should avoid this -- JSON specifies that you should be using double quotes, and many parsing libraries will fail with single quotes now (because strictly speaking, it's not well formatted JSON anymore). – BrainSlugs83 Oct 26 '18 at 19:39

1 Answers1

47

Yes, this is possible. If you use a JsonTextWriter explicitly instead of using JsonConvert.SerializeObject(), you can set the QuoteChar to a single quote.

var obj = new { key = "value" };

StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
    writer.QuoteChar = '\'';

    JsonSerializer ser = new JsonSerializer();
    ser.Serialize(writer, obj);
}

Console.WriteLine(sb.ToString());

Output:

{'key':'value'}

Fiddle: https://dotnetfiddle.net/LGRl1k

Keep in mind that using single quotes around keys and values in JSON is considered non-standard (see JSON.org), and may cause problems for parsers that adhere strictly to the standard.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300