-
Notifications
You must be signed in to change notification settings - Fork 185
fix: (.NET) Improve json De/serialization #1138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
Replaces switch on JsonTokenType with a recursive method using JsonElement.ValueKind for more robust and accurate type inference. This improves handling of nested objects and arrays, and unifies the logic for converting JSON values to .NET types.
Simplifies and standardizes the deserialization of model properties from dictionaries, removing special handling for JsonElement and streamlining array and primitive type conversions. This improves code readability and maintainability in generated model classes.
Updated the From method in the model template to check for the existence of optional properties in the input map before assigning values. This prevents errors when optional properties are missing from the input dictionary. (for examle in model: User, :-/ )
templates/dotnet/Package/Converters/ObjectToInferredTypesConverter.cs.twig
Outdated
Show resolved
Hide resolved
There was a problem hiding this 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 refactors JSON serialization and deserialization in the .NET SDK template to fix critical bugs and improve robustness, particularly addressing infinite recursion issues and type inference problems.
- Fixed infinite recursion bug in
ObjectToInferredTypesConverter
that causedStackOverflowException
- Improved JSON type inference by switching from
JsonTokenType
toJsonElement.ValueKind
- Streamlined model deserialization by removing special
JsonElement
handling and standardizing type conversions
Reviewed Changes
Copilot reviewed 5 out of 6 changed files in this pull request and generated 2 comments.
Show a summary per file
File | Description |
---|---|
templates/dotnet/Package/Role.cs.twig | Updated namespace to use dynamic spec title |
templates/dotnet/Package/Models/Model.cs.twig | Simplified model deserialization logic, removed JsonElement handling |
templates/dotnet/Package/Models/InputFile.cs.twig | Updated namespace import to use dynamic spec title |
templates/dotnet/Package/Exception.cs.twig | Added blank line formatting |
templates/dotnet/Package/Converters/ObjectToInferredTypesConverter.cs.twig | Complete rewrite to fix recursion bug and improve type inference |
Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.
{%- endif %} | ||
{%- else %} | ||
{%- if property.type == 'array' -%} | ||
map["{{ property.name }}"] is JsonElement jsonArrayProp{{ loop.index }} ? jsonArrayProp{{ loop.index }}.Deserialize<{{ property | typeName }}>()! : ({{ property | typeName }})map["{{ property.name }}"] | ||
((IEnumerable<object>)map["{{ property.name }}"]).Select(x => {% if property.items.type == "string" %}x?.ToString(){% elseif property.items.type == "integer" %}{% if not property.required %}x == null ? (long?)null : {% endif %}Convert.ToInt64(x){% elseif property.items.type == "number" %}{% if not property.required %}x == null ? (double?)null : {% endif %}Convert.ToDouble(x){% elseif property.items.type == "boolean" %}{% if not property.required %}x == null ? (bool?)null : {% endif %}(bool)x{% else %}x{% endif %}).{% if property.items.type == "string" and property.required %}Where(x => x != null).{% endif %}ToList()! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The null-forgiving operator !
at the end of ToList()!
could hide potential null reference exceptions. If the enumerable or its elements could be null, this could cause runtime errors.
((IEnumerable<object>)map["{{ property.name }}"]).Select(x => {% if property.items.type == "string" %}x?.ToString(){% elseif property.items.type == "integer" %}{% if not property.required %}x == null ? (long?)null : {% endif %}Convert.ToInt64(x){% elseif property.items.type == "number" %}{% if not property.required %}x == null ? (double?)null : {% endif %}Convert.ToDouble(x){% elseif property.items.type == "boolean" %}{% if not property.required %}x == null ? (bool?)null : {% endif %}(bool)x{% else %}x{% endif %}).{% if property.items.type == "string" and property.required %}Where(x => x != null).{% endif %}ToList()! | |
((map["{{ property.name }}"] as IEnumerable<object>)?.Select(x => {% if property.items.type == "string" %}x?.ToString(){% elseif property.items.type == "integer" %}{% if not property.required %}x == null ? (long?)null : {% endif %}Convert.ToInt64(x){% elseif property.items.type == "number" %}{% if not property.required %}x == null ? (double?)null : {% endif %}Convert.ToDouble(x){% elseif property.items.type == "boolean" %}{% if not property.required %}x == null ? (bool?)null : {% endif %}(bool)x{% else %}x{% endif %}){% if property.items.type == "string" and property.required %}?.Where(x => x != null){% endif %}?.ToList() ?? new List<{% if property.items.type == "string" %}string{% elseif property.items.type == "integer" %}long{% elseif property.items.type == "number" %}double{% elseif property.items.type == "boolean" %}bool{% else %}object{% endif %}>() |
Copilot uses AI. Check for mistakes.
cf7eb57
to
b071cbc
Compare
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughThe converter’s Read method now returns object? and parses via JsonDocument, delegating to a new recursive ConvertElement that maps JsonElement kinds to .NET types and handles null/undefined; unsupported kinds throw JsonException. The generated Exception adds an overload accepting message and inner Exception. Model From methods switch from JsonElement-based parsing to dictionary-centric casts, add optional key guards, and use IEnumerable for arrays and numeric conversions. Role’s namespace becomes templated (spec.title). InputFile’s using is templated to {{ spec.title | caseUcfirst }}.Extensions. Several files add a trailing newline; no other public APIs change. ✨ Finishing Touches🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
templates/dotnet/Package/Query.cs.twig (1)
153-159
: Validate deserialization in Or/And to avoid nulls in ValuesJsonSerializer.Deserialize can return null on malformed input; currently this would silently serialize null entries. Fail fast with a clear error.
public static string Or(List<string> queries) { - return new Query("or", null, queries.Select(q => JsonSerializer.Deserialize<Query>(q, Client.DeserializerOptions)).ToList()).ToString(); + var parsed = queries + .Select(q => JsonSerializer.Deserialize<Query>(q, Client.DeserializerOptions) ?? throw new JsonException("Invalid query JSON in Or()")) + .ToList(); + return new Query("or", null, parsed).ToString(); } public static string And(List<string> queries) { - return new Query("and", null, queries.Select(q => JsonSerializer.Deserialize<Query>(q, Client.DeserializerOptions)).ToList()).ToString(); + var parsed = queries + .Select(q => JsonSerializer.Deserialize<Query>(q, Client.DeserializerOptions) ?? throw new JsonException("Invalid query JSON in And()")) + .ToList(); + return new Query("and", null, parsed).ToString(); }templates/dotnet/Package/Extensions/Extensions.cs.twig (1)
15-38
: Correct query encoding and culture-invariant formattingEncoding the entire string via Uri.EscapeUriString risks malformed queries and culture-specific number formats. Encode components with Uri.EscapeDataString and format numbers with InvariantCulture; normalize booleans to lowercase.
- public static string ToQueryString(this Dictionary<string, object?> parameters) - { - var query = new List<string>(); - - foreach (var kvp in parameters) - { - switch (kvp.Value) - { - case null: - continue; - case IList list: - foreach (var item in list) - { - query.Add($"{kvp.Key}[]={item}"); - } - break; - default: - query.Add($"{kvp.Key}={kvp.Value.ToString()}"); - break; - } - } - - return Uri.EscapeUriString(string.Join("&", query)); - } + public static string ToQueryString(this Dictionary<string, object?> parameters) + { + string Encode(object? v) => + v switch + { + null => string.Empty, + bool b => b ? "true" : "false", + IFormattable f => f.ToString(null, System.Globalization.CultureInfo.InvariantCulture), + _ => v.ToString() ?? string.Empty + }; + + var parts = new List<string>(); + + foreach (var kvp in parameters) + { + switch (kvp.Value) + { + case null: + continue; + case IList list when kvp.Key is not null: + foreach (var item in list) + { + parts.Add($"{kvp.Key}[]={Uri.EscapeDataString(Encode(item))}"); + } + break; + default: + parts.Add($"{kvp.Key}={Uri.EscapeDataString(Encode(kvp.Value))}"); + break; + } + } + + return string.Join("&", parts); + }
♻️ Duplicate comments (2)
templates/dotnet/Package/Converters/ObjectToInferredTypesConverter.cs.twig (1)
72-73
: EOF newline restored.Matches prior request to add terminal newline.
templates/dotnet/Package/Models/Model.cs.twig (1)
51-51
: Remove null-forgiving and tame the long LINQ chain.ToList() never returns null; the bang is unnecessary. Also, this line is hard to read—prior feedback still applies.
- ((IEnumerable<object>)map["{{ property.name }}"]).Select(x => {% if property.items.type == "string" %}x?.ToString(){% elseif property.items.type == "integer" %}{% if not property.required %}x == null ? (long?)null : {% endif %}Convert.ToInt64(x){% elseif property.items.type == "number" %}{% if not property.required %}x == null ? (double?)null : {% endif %}Convert.ToDouble(x){% elseif property.items.type == "boolean" %}{% if not property.required %}x == null ? (bool?)null : {% endif %}(bool)x{% else %}x{% endif %}).{% if property.items.type == "string" and property.required %}Where(x => x != null).{% endif %}ToList()! + ((IEnumerable<object>)map["{{ property.name }}"]).Select(x => {% if property.items.type == "string" %}x?.ToString(){% elseif property.items.type == "integer" %}{% if not property.required %}x == null ? (long?)null : {% endif %}Convert.ToInt64(x){% elseif property.items.type == "number" %}{% if not property.required %}x == null ? (double?)null : {% endif %}Convert.ToDouble(x){% elseif property.items.type == "boolean" %}{% if not property.required %}x == null ? (bool?)null : {% endif %}(bool)x{% else %}x{% endif %}).{% if property.items.type == "string" and property.required %}Where(x => x != null).{% endif %}ToList()Optional: mirror the safe-cast pattern from Lines 45-48 for optionals.
🧹 Nitpick comments (8)
templates/dotnet/Package/Query.cs.twig (1)
25-42
: Broaden handling of enumerable values in constructorToday only IList is expanded; IEnumerable (e.g., LINQ results, HashSet) are treated as a single value. Safely broaden to IEnumerable while avoiding strings.
public Query(string method, string? attribute, object? values) { this.Method = method; this.Attribute = attribute; - if (values is IList valuesList) + if (values is IList valuesList) { this.Values = new List<object>(); foreach (var value in valuesList) { this.Values.Add(value); // Automatically boxes if value is a value type } } - else if (values != null) + else if (values is IEnumerable enumerable && values is not string) + { + this.Values = new List<object>(); + foreach (var value in enumerable) + { + this.Values.Add(value!); + } + } + else if (values != null) { this.Values = new List<object> { values }; } }templates/dotnet/Package/Extensions/Extensions.cs.twig (3)
1-5
: Add missing using for CultureInfo (if not already imported elsewhere)Required by the proposed InvariantCulture formatting.
using System; using System.Collections; using System.Collections.Generic; using System.Text.Json; +using System.Globalization;
40-41
: Make mappings readonlyThis is a constant lookup table; prevent accidental mutation.
- private static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) { + private static readonly IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {
607-612
: Use nameof in ArgumentNullExceptionMinor clarity/readability improvement.
- if (extension == null) - { - throw new ArgumentNullException("extension"); - } + if (extension == null) + { + throw new ArgumentNullException(nameof(extension)); + }templates/dotnet/Package/Models/InputFile.cs.twig (1)
14-21
: Guard against invalid pathsOptional: validate input to avoid surprising runtime errors and provide clearer messages.
- public static InputFile FromPath(string path) => new InputFile + public static InputFile FromPath(string path) + { + if (string.IsNullOrWhiteSpace(path)) + throw new ArgumentException("Path must be a non-empty string.", nameof(path)); + return new InputFile { Path = path, Filename = System.IO.Path.GetFileName(path), MimeType = path.GetMimeType(), SourceType = "path" - }; + }; + }templates/dotnet/Package/Exception.cs.twig (1)
22-25
: Constructor overload looks good; consider serialization support and parity overloads.Nice addition. Two optional tweaks:
- Add [Serializable] + protected (SerializationInfo, StreamingContext) ctor for Exception best practices.
- Consider an overload that also accepts code/type/response with an inner exception if those are commonly set when wrapping.
templates/dotnet/Package/Converters/ObjectToInferredTypesConverter.cs.twig (2)
38-44
: Prefer DateTimeOffset (or skip auto date coercion) to preserve offsets.Parsing string → DateTime can lose timezone info or affect round-tripping when models expect strings. Either:
- Try DateTimeOffset first, then DateTime, else keep string.
- Or, keep all strings as strings (let models decide). First option shown below.
- case JsonValueKind.String: - if (element.TryGetDateTime(out DateTime datetime)) - { - return datetime; - } - return element.GetString(); + case JsonValueKind.String: + if (element.TryGetDateTimeOffset(out DateTimeOffset dto)) + { + return dto; + } + if (element.TryGetDateTime(out DateTime dt)) + { + return dt; + } + return element.GetString();
45-51
: Avoid precision loss for large/monetary numbers.Fall back to decimal before double to preserve precision; Convert.* in models will still handle decimal.
case JsonValueKind.Number: if (element.TryGetInt64(out long l)) { return l; } - return element.GetDouble(); + if (element.TryGetDecimal(out decimal dec)) + { + return dec; + } + return element.GetDouble();
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (8)
templates/dotnet/Package/Converters/ObjectToInferredTypesConverter.cs.twig
(1 hunks)templates/dotnet/Package/Exception.cs.twig
(1 hunks)templates/dotnet/Package/Extensions/Extensions.cs.twig
(1 hunks)templates/dotnet/Package/Models/InputFile.cs.twig
(2 hunks)templates/dotnet/Package/Models/Model.cs.twig
(1 hunks)templates/dotnet/Package/Models/UploadProgress.cs.twig
(1 hunks)templates/dotnet/Package/Query.cs.twig
(1 hunks)templates/dotnet/Package/Role.cs.twig
(2 hunks)
🔇 Additional comments (3)
templates/dotnet/Package/Models/UploadProgress.cs.twig (1)
1-26
: LGTM — formatting onlyNo functional changes. Safe.
templates/dotnet/Package/Role.cs.twig (1)
1-92
: LGTM — namespace templatingNamespace templating aligns with the rest of the PR; no functional changes to Role API.
templates/dotnet/Package/Converters/ObjectToInferredTypesConverter.cs.twig (1)
10-16
: Good fix: eliminates recursion/StackOverflow and handles nulls cleanly.Using JsonDocument + a single pass is safer and clearer. No issues here.
{%- if not property.required -%}map.ContainsKey("{{ property.name }}") ? {% endif %} | ||
{%- if property.sub_schema %} | ||
{%- if property.type == 'array' -%} | ||
map["{{ property.name }}"] is JsonElement jsonArray{{ loop.index }} ? jsonArray{{ loop.index }}.Deserialize<List<Dictionary<string, object>>>()!.Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: it)).ToList() : ((IEnumerable<Dictionary<string, object>>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: it)).ToList() | ||
((IEnumerable<object>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it)).ToList() | ||
{%- else -%} | ||
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: map["{{ property.name }}"] is JsonElement jsonObj{{ loop.index }} ? jsonObj{{ loop.index }}.Deserialize<Dictionary<string, object>>()! : (Dictionary<string, object>)map["{{ property.name }}"]) | ||
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)map["{{ property.name }}"]) | ||
{%- endif %} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Optional key guard misses the “present-but-null” case (can throw).
If the key exists with null, casts below will NRE/ICE. Guard for null too.
- {%- if not property.required -%}map.ContainsKey("{{ property.name }}") ? {% endif %}
+ {%- if not property.required -%}map.ContainsKey("{{ property.name }}") && map["{{ property.name }}"] != null ? {% endif %}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
{%- if not property.required -%}map.ContainsKey("{{ property.name }}") ? {% endif %} | |
{%- if property.sub_schema %} | |
{%- if property.type == 'array' -%} | |
map["{{ property.name }}"] is JsonElement jsonArray{{ loop.index }} ? jsonArray{{ loop.index }}.Deserialize<List<Dictionary<string, object>>>()!.Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: it)).ToList() : ((IEnumerable<Dictionary<string, object>>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: it)).ToList() | |
((IEnumerable<object>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it)).ToList() | |
{%- else -%} | |
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: map["{{ property.name }}"] is JsonElement jsonObj{{ loop.index }} ? jsonObj{{ loop.index }}.Deserialize<Dictionary<string, object>>()! : (Dictionary<string, object>)map["{{ property.name }}"]) | |
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)map["{{ property.name }}"]) | |
{%- endif %} | |
{%- if not property.required -%}map.ContainsKey("{{ property.name }}") && map["{{ property.name }}"] != null ? {% endif %} | |
{%- if property.sub_schema %} | |
{%- if property.type == 'array' -%} | |
((IEnumerable<object>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it)).ToList() | |
{%- else -%} | |
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)map["{{ property.name }}"]) | |
{%- endif %} |
🤖 Prompt for AI Agents
In templates/dotnet/Package/Models/Model.cs.twig around lines 42 to 48, the
optional-key guard only checks map.ContainsKey("{{ property.name }}") and will
still attempt casts when the key is present but null; update the guard to also
verify the value is not null (e.g., check map.ContainsKey(...) && map["{{
property.name }}"] != null or use TryGetValue to obtain the value and test for
null) before performing any casts or Select/ToList calls, and apply this null
check to both the array and object branches so null values do not cause NRE/ICE.
((IEnumerable<object>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it)).ToList() | ||
{%- else -%} | ||
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: map["{{ property.name }}"] is JsonElement jsonObj{{ loop.index }} ? jsonObj{{ loop.index }}.Deserialize<Dictionary<string, object>>()! : (Dictionary<string, object>)map["{{ property.name }}"]) | ||
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)map["{{ property.name }}"]) | ||
{%- endif %} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Safer casts for sub-schemas (avoid InvalidCast when value types deviate).
Use safe casts for optionals to prevent InvalidCastException when value is null/mismatched.
- ((IEnumerable<object>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it)).ToList()
+ ((map["{{ property.name }}"] as IEnumerable<object>) ?? Array.Empty<object>())
+ .Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it))
+ .ToList()
- {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)map["{{ property.name }}"])
+ (map["{{ property.name }}"] as Dictionary<string, object>) is { } obj
+ ? {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: obj)
+ : null
Note: The second change pairs with the Line 42 null-guard; harmless for required props, safer for optionals.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
((IEnumerable<object>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it)).ToList() | |
{%- else -%} | |
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: map["{{ property.name }}"] is JsonElement jsonObj{{ loop.index }} ? jsonObj{{ loop.index }}.Deserialize<Dictionary<string, object>>()! : (Dictionary<string, object>)map["{{ property.name }}"]) | |
{{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)map["{{ property.name }}"]) | |
{%- endif %} | |
((map["{{ property.name }}"] as IEnumerable<object>) ?? Array.Empty<object>()) | |
.Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it)) | |
.ToList() | |
{%- else -%} | |
(map["{{ property.name }}"] as Dictionary<string, object>) is { } obj | |
? {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: obj) | |
: null | |
{%- endif %} |
🤖 Prompt for AI Agents
In templates/dotnet/Package/Models/Model.cs.twig around lines 45-48, avoid
direct casts that throw InvalidCastException by using safe casts and null
guards: replace ((IEnumerable<object>)map["{{ property.name }}"]) with a safe
cast (as IEnumerable<object>) and handle null by either using ?.Select(...)
followed by ToList() or coalescing to an empty sequence before mapping;
similarly replace (Dictionary<string, object>)map["{{ property.name }}"] with a
safe cast (as Dictionary<string, object>) and only call {{ property.sub_schema |
caseUcfirst | overrideIdentifier }}.From when the result is non-null (or pass a
null-safe value), keeping the existing Line 42 null-guard pairing for optionals.
map["{{ property.name }}"].ToString() | ||
{%- endif %} | ||
{%- else -%} | ||
map["{{ property.name }}"]{% if not property.required %}?{% endif %}.ToString() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Preserve ISO strings when converter produced DateTime/Offset.
If the converter inferred DateTime/Offset, ToString() becomes culture-dependent. Emit ISO 8601 for round-trip.
- map["{{ property.name }}"]{% if not property.required %}?{% endif %}.ToString()
+ map["{{ property.name }}"] switch
+ {
+ DateTimeOffset dto => dto.ToString("O"),
+ DateTime dt => dt.ToUniversalTime().ToString("O"),
+ _ => map["{{ property.name }}"]{% if not property.required %}?{% endif %}.ToString()
+ }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
map["{{ property.name }}"]{% if not property.required %}?{% endif %}.ToString() | |
map["{{ property.name }}"]{% if not property.required %}?{% endif %} switch | |
{ | |
DateTimeOffset dto => dto.ToString("O"), | |
DateTime dt => dt.ToUniversalTime().ToString("O"), | |
_ => map["{{ property.name }}"]{% if not property.required %}?{% endif %}.ToString() | |
} |
🤖 Prompt for AI Agents
In templates/dotnet/Package/Models/Model.cs.twig around line 59, the template
calls ToString() on values that a converter may have produced as
DateTime/DateTimeOffset, which is culture-dependent; update the template to emit
an ISO 8601 round-trip representation by using ToString("o") for DateTime and
DateTimeOffset cases (respecting the existing nullability ? operator if
present). Detect the property type (e.g., property.type == "DateTime" or
property.type == "DateTimeOffset" or equivalent metadata your generator
provides) and replace ToString() with ToString("o") only for those types,
leaving other types unchanged.
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
Summary by CodeRabbit
New Features
Bug Fixes
Refactor