3

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.

3
  • Can confirm this one is not a duplicate of that post Commented Nov 27, 2021 at 18:53
  • I am sorry your question got closed, I believe it's a bug and sent a report here. In the meantime, I suggest switching to Dictionary or anonymous type if possible instead of ExpandoObject. Commented Nov 27, 2021 at 19:13
  • 1
    Found the fix for you btw, check this comment. ExpandoObject is considered Dictionary, so you need to set DictionaryKeyPolicy instead of PropertyNamingPolicy. Commented Nov 27, 2021 at 19:40

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.