Skip to content

JsonSerializer don't respect PropertyNamingPolicy when serializing ExpandoObjects containing ExpandoObjects #42440

Closed
@petterlabraaten

Description

@petterlabraaten

I expect this test to pass, but it seems that PropertyNamingPolicy is ignored when serializing property names of ExpandoObjects contained within other ExpandoObjects:

public class TestClass
{
    public ExpandoObject OuterProperty { get; } = new ExpandoObject();

    public TestClass()
    {
        ((dynamic)OuterProperty).InnerProperty = new ExpandoObject();
    }
}

[Fact]
public void TestExpandoSerialization()
{
    var a = new TestClass();

    JsonSerializerOptions options = new JsonSerializerOptions()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
    };

    var result = JsonSerializer.Serialize(a, options);

    string expected = "{\"outerProperty\":{\"innerProperty\":{}}}";
    Assert.Equal(expected, result);
}
Message: 
    Assert.Equal() Failure
                                 ↓ (pos 19)
    Expected: {"outerProperty":{"innerProperty":{}}}
    Actual:   {"outerProperty":{"InnerProperty":{}}}
                                 ↑ (pos 19)

If I change the type of InnerProperty , to an integer for instance, PropertyNamingPolicy is treated as expected:

public class TestClass
{
    public ExpandoObject OuterProperty { get; } = new ExpandoObject();

    public TestClass()
    {
        ((dynamic)OuterProperty).InnerProperty = 5;
    }
}

[Fact]
public void TestExpandoSerialization()
{
    var a = new TestClass();

    JsonSerializerOptions options = new JsonSerializerOptions()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
    };

    var result = JsonSerializer.Serialize(a, options);

    string expected = "{\"outerProperty\":{\"innerProperty\":5}}";
    Assert.Equal(expected, result);
}

.Net Core version: 3.1.302

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions