Skip to content
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

String -> Json serialization #2089

Open
marekvinkler opened this issue May 31, 2023 · 4 comments
Open

String -> Json serialization #2089

marekvinkler opened this issue May 31, 2023 · 4 comments

Comments

@marekvinkler
Copy link

I'm actually continuing discussion on this bug: #1886

I have to send an arbitrary object via RestSharp. Currently the only possibility for me is to add the body via AddParameter(new JsonParameter("", json)) which seems quite ugly to me. It would be nice to add the bool forceSerialize parameter also to the generic AddJsonBody and not only to the string specialization. That way I could make sure that AddJsonBody serializes the object to a valid JSON for every type.

@alexeyzimarev
Copy link
Member

It's already there and described in the docs:

image

@marekvinkler
Copy link
Author

The example you sent is for the string specialization, in other words, when the compiler knows the payload is a string.

But I would like a method that serializes any runtime type correctly, e.g.
image
or even
image
Here, the compile time type is a string array (or any other structure) or object type leading to a compile time error.

I think the method could look like this:

public static RestRequest AddJsonBody<T>(this RestRequest request, T obj, bool forceSerialize, ContentType? contentType = null) where T : class
{
    request.RequestFormat = DataFormat.Json;

    return obj is string str && !forceSerialize
        ? request.AddStringBody(str, DataFormat.Json)
        : request.AddParameter(new JsonParameter(obj, contentType));
}

@alexeyzimarev
Copy link
Member

The idea is good, but I don't like the API ambiguity. It's quote unclear that you pass an object and then have an option to set forceSerialize to false, and it will do nothing at all. Isn't it confusing?

@marekvinkler
Copy link
Author

I probably don't fully understand your concern. With forceSerialize = false the behavior is exactly the same as for the already existing method:

public static RestRequest AddJsonBody<T>(this RestRequest request, T obj, ContentType? contentType = null) where T : class {

In other words, the existing code will work exactly the same as it does now (not serializing strings).

The advantage of the optional forceSerialize = true is that you will get a valid json for any input type, which is what I believe the AddJsonBody method should do (though I get that for backwards compatibility it is not possible to make it a default behavior).

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

No branches or pull requests

2 participants