fix: (.NET) Improve json De/serialization #1138
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What does this PR do?
This PR refactors the JSON serialization and deserialization logic in the .NET SDK template to improve robustness and fix critical issues:
Key Changes:
Fixed infinite recursion bug in
ObjectToInferredTypesConverter
: Replaced the problematic approach of usingJsonSerializer.Deserialize
recursively within the converter itself, which causedStackOverflowException
for nested objects and arrays.Improved JSON type inference: Switched from
JsonTokenType
toJsonElement.ValueKind
for more accurate and reliable type detection, providing better handling of all JSON value types including null and undefined values.Eliminates the risk of leaking JsonElement instances into the resulting object graph, simplifying model deserialization and removing the need for special handling of JsonElement in generated code.
Streamlined model deserialization: Simplified the generated model deserialization logic by removing special handling for
JsonElement
objects and standardizing type conversions, making the generated code more readable and maintainable.Enhanced error handling: Added proper error handling with descriptive exceptions for unsupported JSON value kinds.
Test Plan
Testing the ObjectToInferredTypesConverter fix:
Testing model deserialization changes:
Related PRs and Issues
This PR addresses potential runtime crashes and improves the overall reliability of JSON handling in generated .NET SDKs. The changes are particularly important for applications that work with complex nested JSON structures from API responses.
Related to issues with incorrect type mapping, JsonElement leakage, and runtime errors during deserialization of complex/nested JSON structures.
Have you read the Contributing Guidelines on issues?
YES