Skip to content

Fix errors when converting response bodies with top-level JSON arrays to C# code#1301

Merged
StefH merged 1 commit intowiremock:masterfrom
asaf92:fix/json-array-parsing
May 22, 2025
Merged

Fix errors when converting response bodies with top-level JSON arrays to C# code#1301
StefH merged 1 commit intowiremock:masterfrom
asaf92:fix/json-array-parsing

Conversation

@asaf92
Copy link
Copy Markdown
Contributor

@asaf92 asaf92 commented May 21, 2025

When trying to convert static mapping to C# code, I ran into an exception when the body is a top-level array rather than a pure string or a (non-array) JSON object.

The problem is that this code doesn't distinguish between arrays and objects, and assumes that every non-null that isn't a string is an object:

case BodyType.Json:
    if (bodyData.BodyAsJson is string bodyStringValue)
    {
        sb.AppendLine($"        .WithBody({ToCSharpStringLiteral(bodyStringValue)})");
    }
    else if (bodyData.BodyAsJson is { } jsonBody)
    {
        var anonymousObjectDefinition = ConvertToAnonymousObjectDefinition(jsonBody);
        sb.AppendLine($"        .WithBodyAsJson({anonymousObjectDefinition})");
    }
                                                                                      
    break;

My solution is to load a JToken instead of a JObject in ConvertToAnonymousObjectDefinition, which seems like the original intention given that ConvertJsonToAnonymousObjectDefinition (which is defined in an internal class) expects a JToken and isn't called anywhere else in the code.

@StefH StefH added the bug Something isn't working label May 21, 2025
@StefH StefH self-requested a review May 21, 2025 20:32
Copy link
Copy Markdown
Collaborator

@StefH StefH left a comment

Choose a reason for hiding this comment

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

Can you also add a unit test?

@StefH StefH merged commit b4279be into wiremock:master May 22, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants