How to serialize a JObject just like an object with Json.NET?

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:

// startup.cs has the following
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?

+4
source share
2 answers

a JObject , JSON . JsonSerializerSettings JSON.

-1

, , - JObject string, ExpandoObject ( object, a JObject). ExpandoObject , , JsonConvert . , Newtonsoft.Json JObject , , , , , , .

:

// Construct a JObject.
var jObject = JObject.Parse("{ SomeName: \"Some value\" }");

// Deserialize the object into an ExpandoObject (don't use object, because you will get a JObject).
var payload = JsonConvert.DeserializeObject<ExpandoObject>(jObject.ToString());

// Now you can serialize the object using any serializer settings you like.
var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new CamelCaseNamingStrategy
        {
            // Important! Make sure to set this to true, since an ExpandoObject is like a dictionary.
            ProcessDictionaryKeys = true,
        }
    }
}
);

Console.WriteLine(json); // Outputs: {"someName":"Some value"}

ExpandoObject : JObject CamelCase JSON.Net

0

Source: https://habr.com/ru/post/1658838/


All Articles