The following code:
var json = JsonConvert.SerializeObject(fooObject,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
});
Seralizes a json (string) object of:
{ "fooA":0, "fooB":0, "fooC":false, "fooD":false, "fooE":0, "fooF":0, }
The values are not in quotation marks, such as "fooA":"0". This is the behavior that I want.
Is there a way to enforce this behavior?
In JSON format, numbers and booleans do not have quotes around them, while strings do (see JSON.org).
If you want quotes around all your primitives, you have a few options:
string
.Dictionary<string, string>
(or a DTO) and serialize that instead.JsonConverter
to do the conversion. This option has the advantage that it can apply globally so that you don't have to change all your classes.The first two options are pretty self-explanatory. If you opted to go with a converter, the code might look something like this:
To use it, simply pass an instance of the converter to the
JsonConvert.SerializeObject
method.Demo:
Output: