Skip to content

AddJsonBody handles strings in a usually user-friendly but incorrect way #1954

Description

@MattiasMartens

Describe the bug

When calling AddJsonBody() with a string, what is added is the literal string supplied without serialization. This makes it impossible to handle the case where the value is a JSON object whose full and complete structure is "String".

To Reproduce

The RestSharp code involved is trivial, see the body of AddJsonBody():

request.RequestFormat=DataFormat.Json;returnobjisstringstr?request.AddStringBody(str,DataFormat.Json):request.AddParameter(newJsonParameter("",obj,contentType));

In our case, the API we're hitting has this type stanza:

"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "string"
}
}
}
},

Importantly, the backend expects this input to be the serialized version of a JSON object (I know, I know). So to call it properly, naively we expected to be able to do:

request.AddJsonBody(JsonConvert.SerializeObject(myObject))

But of course this does not work -- it hits the first part of the ternary above and treats it as "already serialized", sending the string as-is. This causes it to be parsed as an object by the middleware, not as a string as intended.

Instead, this is currently what we have to do:

request.AddJsonBody(JsonConvert.SerializeObject(JsonConvert.SerializeObject(myObject)))

(Note that in the real world it's not as simple as this -- we are calling RestSharp through a generated client, so we don't have the option of calling a different more appropriate method even if there is one.)

Expected behavior

There should be a way to add a top-level string as JSON, serializing it as expected. Top-level strings are valid JSON!

I understand that the current implementation probably avoids some common gotchas, but it is important to handle this case as well, because there really are APIs in the wild that require JSON-formatted top-level strings as input. In our case, this issue required a lot of debugging to figure out.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions