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

1

1

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.

Aracelyaraceous answered 8/7, 2016 at 9:34 Comment(0)
N
1

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);
Nitrogenous answered 8/7, 2016 at 9:39 Comment(1)
Thanks for your reply. When I try the API thanks to POSTMAN with contentType application/json and a JSON object in the body, I receive a 400 bad request, I don't even enter myMethod. It works when I send an object formatted this way: "{\"key1\":\"value1\",...}" Don't know why I tried with the python double backslashes and not with single backslashes..Aracelyaraceous

© 2022 - 2024 — McMap. All rights reserved.