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?
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.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With