1

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.

dbc
  • 91,441
  • 18
  • 186
  • 284
Hossein Fallah
  • 923
  • 4
  • 16
  • Can confirm this one is not a duplicate of that post – Luke Vo Nov 27 '21 at 18:53
  • I am sorry your question got closed, I believe it's a bug and sent a report [here](https://github.com/dotnet/runtime/issues/62101). In the meantime, I suggest switching to Dictionary or anonymous type if possible instead of `ExpandoObject`. – Luke Vo Nov 27 '21 at 19:13
  • 1
    Found the fix for you btw, check [this comment](https://github.com/dotnet/runtime/issues/62101#issuecomment-980790290). `ExpandoObject` is considered Dictionary, so you need to set `DictionaryKeyPolicy` instead of `PropertyNamingPolicy`. – Luke Vo Nov 27 '21 at 19:40

1 Answers1

3

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"}}

Guru Stron
  • 42,843
  • 5
  • 48
  • 70