Zahir J
Zahir J

Reputation: 1179

Remove double quotes from JSON.SerializeObject string property

I have a class that when serialized using Newtonsoft's JsonConvert.SerializeObject method returns a JSON object similar to:

{"id":8,"name":"floating-point","colour":"blue"}

Here the property value "blue" is a quoted string because in my class colour is a string.

This object is a node in a graph and the colour property is used to colour the node. What I want to do is tell the method using this colour property to get the colour from a Javascript function like so

{"id":8,"name":"floating-point","colour":getColour('floating-point')}

(that does work). I don't need

{"id":8,"name":"floating-point","colour":"getColour('floating-point')"}

I'm using a 3rd party visualization tool that generates the graph so I can't intercept/pre-process the colour property.

How do I remove the double-quote surrounding the value of the colour property when it is serialized?

Upvotes: 2

Views: 9259

Answers (1)

user310988
user310988

Reputation:

You can use a JsonConverter attribute to control the serialization of the value.

Technically this will no longer be JSON, but it sounds like you have a specific use-case which requires this.

I'm using a 3rd party visualization tool that generates the graph so I can't intercept/pre-process the colour property.

Source: https://blog.bitscry.com/2017/10/23/serializing-json-values-without-quotes/

You can make the JsonConverter like this:

public class PlainJsonStringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value;
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteRawValue((string)value);
    }
}

And use it like this:

public class Config
{
    public string ID { get; set; }

    public string Name { get; set; }

    [JsonConverter(typeof(PlainJsonStringConverter))]
    public string Colour{ get; set; }
}

Here's a DotNetFiddle showing it working: https://dotnetfiddle.net/dhIjvT

And this is the output {"ID":"8","Name":"floating-point","Colour":getColour('floating-point')}

Upvotes: 6

Related Questions