dotnet / dotnet/aspnetcore

JSON Patch PocoAdapter does not utilize the contract resolver when converting values.

Open
#54,178 0 comments 0 reactions 0 assignees View on GitHub
area-mvc feature-json-patch
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

Applying a JSON Patch Document to a POCO should respect the provided IContractResolver.

Specifically, within PocoAdapter.TryReplace, the contract resolver is used to get the json property, however that resolver is not passed to TryConvertValue, thus the converted value does not utilize the resolver.

### Expected Behavior

I should be able to pass a custom contract resolver and have that resolver's converters be applied.

Roughly, the following code would be modified:
1. PocoAdapter.TryReplace would pass IContractResolver to PocoAdapter.TryConvertValue
2. PocoAdapter.TryConvertValue would pass the contract resolver to ConversionResultProvider.ConvertTo

The changes will support the ability to pass custom converters provided by the contract provider.

### Steps To Reproduce

Use the following classes and contract resolver to apply a patch operation.

```
public enum MyEnum {
Active,
Inactive,
}
```

```
public class MyPoco {
public MyEnum Status {get;set;}
}
```

```
public class CustomCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);

if (member is PropertyInfo info && info.PropertyType.IsEnum)
{
property.Converter = new StringEnumConverter(new DefaultNamingStrategy(), allowIntegerValues: false);
}

return property;
}
}
```

```
var dto = new MyPoco { Status = Inactive };
var patchdoc = new JsonPatchDocument() { op = "replace", path = "/status", value = "0" };
patchdoc.Apply(dto);
// Expect a failure because the applied contract resolver should not have found a value for MyEnum as integers are not allowed.
```

### Exceptions (if any)

_No response_

### .NET Version

dotnet 6

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.