Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object to json with jsonconvert - without - key-quotations

Tags:

json

c#

I use jsonconvert to convert simple objects to json like

JsonConvert.SerializeObject(new { label = "MyLabel1" });

to

{ "label":"MyLabel1" }

but i want to get the keys without quotation like

{ label: "MyLabel1"}

is there a way to convert objects to json withoud "key"-quotations by using jsonconvert?

like image 516
Matthias Meyer Avatar asked Nov 01 '11 14:11

Matthias Meyer


People also ask

Do JSON values need quotes?

JavaScript object literals do not require quotes around a key name if the key is a valid identifier and not a reserved word. However, JSON always requires quotes around key names.

What is Jsonconvert SerializeObject in C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

Any library that expects JSON or actual JavaScript notation for creating objects (which is a superset of JSON) should work fine with quotes.

But if you really want to remove them, you can set JsonTextWriter.QuoteName to false. Doing this requires writing some code that JsonConvert.SerializeObject() uses by hand:

private static string SerializeWithoutQuote(object value)
{
    var serializer = JsonSerializer.Create(null);

    var stringWriter = new StringWriter();

    using (var jsonWriter = new JsonTextWriter(stringWriter))
    {
        jsonWriter.QuoteName = false;

        serializer.Serialize(jsonWriter, value);

        return stringWriter.ToString();
    }
}
like image 194
svick Avatar answered Oct 12 '22 19:10

svick