How to control JObject serialization for string?
I have some APIs that return a JObject, and I usually apply some changes and save them or return. I want to avoid preserving null properties and apply some additional formatting, but JsonConvert seems to completely ignore my settings.
Here is an example of a problem:
services.AddMvc().AddJsonOptions(o =>
{
o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
public class SampleController : Controller
{
JsonSerializerSettings _settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
[HttpPost]
[Route("object")]
public object PostObject([FromBody] SomeObject data)
{
return JsonConvert.SerializeObject(data, _settings);
}
[HttpPost]
[Route("jobject")]
public object PostJObject([FromBody] JObject data)
{
return JsonConvert.SerializeObject(data, _settings);
}
public class SomeObject
{
public string Foo { get; set; }
public string Bar { get; set; }
}
}
Wiring { "Foo": "Foo", "Bar": null }:
/object returns {"Foo":"Foo"}/jobject returns {"Foo":"Foo","Bar":null}
I want the JObject method to return the same json output, as if I were using an object. How can I achieve this without creating helpers? Is there a way to serialize a JObject using the same settings?
Natan source
share