Search code examples
c#jsonparsinganonymouswebinvoke

"Unexpected character encountered while parsing value: S. Path '', line 0, position 0"


I use multiple APIs coded in C# that work well. I want to use one receiving an anonymous object (I don't want to create a Class). I have a problem when I try to deserialize the object.

I have an API following this scheme, it works well when it's called from python using the json_dumps function. But when I try with JSON.stringify (from an a or even POSTMAN, I have a 400 bad request.

Here is my code, I have tried a lot of things:

[WebInvoke(Method = "POST", UriTemplate = "myUrl")]
[OperationContract]
public Message myMethod(object objectSentByUser)
{
        
    var perso = JsonConvert.DeserializeObject<dynamic>(objectSentByUser.ToString());

JsonConvert.DeserializeObject<dynamic> waits for a string, I tried:

  • to specify objectSentByUser as a string in the argument of myMethod When I do so, I've got a 400 without even entering the method (I tried to send a JSON, to add quotes, to send a string etc...)

  • to cast with (string)objectSentByUser, it doesn't work

  • to use the toString() method, which leads to the next error:

    Unexpected character encountered while parsing value: S. Path '', line 0, position 0

    which is quite normal because objectSentByUser.toString() returns "System.Object". But why does it work when used with python json_dump?

This code works when called with python function json_dump that returns an object like this:

"{\\\"key1\\\":\\\"value1\\\",...}"

From Postman I send a classic POST with application/json as contentType and valid JSON in the body.


Solution

  • If the user sends a valid json string to your action, then don't accept an object as a parameter, but rather a string (i.e. because your user sends you one).

    If you call ToString() on an object, chances are, it's not in a Json format.

    Try accepting a string and deserializing that:

    [WebInvoke(Method = "POST", UriTemplate = "myUrl")]
    [OperationContract]
    public Message myMethod(string jsonSentByUser)
    {
    
        var perso = JsonConvert.DeserializeObject<dynamic>(jsonSentByUser);