Search code examples
c#json.net

How to force serializer to not write quotes for values of specific properties?


If I do the following:

new JProperty("propertyName", 3);

In the json I'll get property value without quotes:

{
...
"propertyName": 3
}

How do I force the serializer to do the same for one particular string property? I.e. I have

new JProperty("propertyName2", "{value2}");
new JProperty("propertyName3", "{{value3}}");

And I'll get this:

{
...
"propertyName2": "{value2}",
"propertyName3": "{{value3}}"
}

How do I force the serializer to do this?

{
...
"propertyName2": "{value2}",
"propertyName3" : {{value3}}
}

Reason I need to produce invalid json is that I'm generating Postman collection json, and this double curly bracket syntax is how Postman replaces variables with actual values. So in this case variable {{value3}} will be replaced by some number later, which means that it has to be without quotes.


Solution

  • You can use JRaw to insert an arbitrary raw text value into a JToken hierarchy.

    Thus:

    var obj = new JObject
    {
        new JProperty("propertyName2", "{value2}"),
        new JProperty("propertyName3", new JRaw("{{value3}}")),
    };
    

    Results in the following (malformed) JSON, as required:

    {
      "propertyName2": "{value2}",
      "propertyName3": {{value3}}
    }
    

    Of course if the raw text is malformed JSON then the overall JSON thereby generated will be malformed and so a JSON parser will be unable to parse it back.

    Demo fiddle here.