c# API “Unexpected character encountered while parsing value: S. Path '', line 0, position 0”

走远了吗. 提交于 2019-12-12 03:23:51

问题


I use multiple API coded in c# that works 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 a valid JSON in the body (verified on a website found in an another discussion on stackoverflow)

Thanks a lot for your help

See you


回答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);


来源:https://stackoverflow.com/questions/38263368/c-sharp-api-unexpected-character-encountered-while-parsing-value-s-path-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!