2

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
  • 104,963
  • 20
  • 228
  • 340
Hossein Fallah
  • 1,859
  • 2
  • 18
  • 44
  • 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

4

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
  • 102,774
  • 10
  • 95
  • 132