Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@VedikaGupt
Copy link

Fixes #7178

This PR fixes a serialization failure in PolymorphicObjectConverter.Write when a value is serialized as a primitive by another converter.
Previously, the converter assumed the serialized JsonElement would always be an object or array and attempted to enumerate it as such. When the value was a primitive (e.g. number), this resulted in a runtime exception during serialization.
The fix adds a defensive check to detect non-object and non-array JsonElement values and writes them directly to the output instead of assuming an object structure.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a serialization crash in PolymorphicObjectConverter when handling types with custom converters that serialize to primitive values (e.g., numbers, booleans). Previously, the converter assumed all serialized values would be objects or arrays and attempted to enumerate them, causing an InvalidOperationException when encountering primitives. The fix adds a defensive check to detect and handle primitive JsonElement values by writing them directly to the output.

Changes:

  • Added a check in PolymorphicObjectConverter.Write to detect non-object, non-array JSON values and write them directly instead of attempting to enumerate properties
  • Resolves issue #7178 where custom converters that serialize to primitive values would crash during serialization

@VedikaGupt
Copy link
Author

VedikaGupt commented Jan 27, 2026

Thanks for the review. I’ve added an integration test in Serialization/Polymorphism/Tests.cs that serializes a type with a custom converter producing a primitive value and verifies it succeeds and outputs the expected primitive JSON. This directly covers the scenario described in #7178. cc @sfmskywalker

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PolymorphicObjectConverter crashes with a type that converts to a primitive

1 participant