Search code examples
c#jsonasp.net-coresystem.text.jsoncamelcasing

System.Text.Json does not camelize properties of the dynamic property


I'm using ASP.NET Core and System.Text.Json.

Here's my sample action method:

    [HttpGet]
    public object Person()
    {
        dynamic relatedItems = new ExpandoObject();
        relatedItems.LastName = "Last";
        var result = new 
        {
            FirstName = "First",
            RelatedItems = relatedItems
        };
        return result;
    }

And here's what I get in response:

{
    firstName: "First",
    relatedItems: {
        LastName: "Last"
    }
}

As you can see, LastName which is a property of the dynamic property, is not camelized.

How can I make everything return in camel case?

Update. That answer is not my answer. As you can see I already have firstName property being correctly camelized.


Solution

  • ExpandoObject will be treated as dictionary, so you need to set DictionaryKeyPolicy in addition to PropertyNamingPolicy:

    dynamic relatedItems = new ExpandoObject();
    relatedItems.LastName = "Last";
    var result = new 
    {
        FirstName = "First",
        RelatedItems = relatedItems
    };
    var s = JsonSerializer.Serialize(result, new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
    });
    Console.WriteLine(s); // prints {"firstName":"First","relatedItems":{"lastName":"Last"}}