Skip to content

Odd dynamic effect with JObject #3640

@jamescurran

Description

@jamescurran

Source/destination types

Gist: https://gist.github.com/jamescurran/fb13fa7563edf8d9e96cf04aab723f99

class Foo
{
	public int A { get; set; }
	public int? Bbb { get; set; }
	public string  C { get; set; }
	public int D { get; set; }
}

	var target = new Foo
	{
		A=123,
		Bbb=456,
		C = "Hello",
		D = 789
	};

	dynamic overlay = ExpandoObject(); //  new  JObject(); //

	overlay.A = (int) 888;
	overlay.Bbb = (int) 999;
	overlay.C = "Greetings";

Mapping configuration

	var configuration = new MapperConfiguration(cfg => { });
	var mapper = new Mapper(configuration);

	mapper.Map<dynamic, Foo>(overlay,target);

Version: 13.0.1

Expected behavior

A | 888
Bbb | 999
C | Greetings
D | 789

The value for properties A, Bbb, and C are changed, and the non-matching field D is unchanged.

Actual behavior

We get the expected behavior when using ExpandoObject. However, if we use JObject (which is what JSON.NET will give you if you deserialize to a dynamic, we get the following:

A | 123
Bbb | 456
C | Greetings
D | 0

The int properties are not changed, the string property is changed, and the non-matching field D set to zero.

Steps to reproduce

	mapper.Map<dynamic, Foo>(overlay,target);

Real-world scenario which led to this

SPA app for editing a user record. The update is made through a webservice API that receives a JSON object with just the changed fields, so object structure changes on every call, so it must be received as a dynamic.

        [HttpPost("UpdateUser")]
         public async Task<JsonResult> UpdateUser([FromBody] dynamic updates) {....}

When using JSON.NET that dynamic object is actually a JObject

Workaround (for my situation)

Force use of ExpandoObject

        [HttpPost("UpdateUser")]
         public async Task<JsonResult> UpdateUser([FromBody] ExpandoObject updates) {....}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions