简体   繁体   中英

Passing Json to the Web Service

I'm trying to push json data to the webservice;

Here is my sample data;

    {
       "data" : {
       "username" : "demo",
       "password" : "demo1082*098/*42a", 
       "LoginToken" :     "AAFF540EC55DASEFBE7E3D8404AED31F6DD30CA2BFCE2433B9475E696GG38730"
       }
    }

Here is my webservice;

public string Post([FromBody]string data)
List<Login> datas = JsonConvert.DeserializeObject<List<Login>>(data);

Error; An exception of type 'System.ArgumentNullException' occurred in Newtonsoft.Json.dll but was not handled in user code

Data appears as NULL

I'm using WebAPI, restful api, C#, visual std 2015

Thanks in Advance.

EDIT;

I'm using DHC chrome extention to POST data. HEADER; Content-Type: application/json BODY;

{
           "data" : {
           "username" : "demo",
           "password" : "demo1082*098/*42a", 
           "LoginToken" :     "AAFF540EC55DASEFBE7E3D8404AED31F6DD30CA2BFCE2433B9475E696GG38730"
           }
        }

Error;

500 Internal Server Error

EDIT; I fount the error which is beacause of "string" kind of data. I solved the problem when I change it as "dynamic". Can someone recommend me a keyword instead of dynamic ?

1) You have to create a class like

public class LoginData
{
    public string username {get;set;}
    public string password {get;set;}
    public string LoginToken {get;set;}
}

and in your web service use like following

public string Post([FromBody]LoginData data)

2) I seen following line that you already created a class name Login (if you have single record in json)

Login datas = JsonConvert.DeserializeObject<Login>(data);

So you also can use

public string Post([FromBody]Login data)

One of the way to do it as follows,

Create class of your request

    public class Data
{
    public string username { get; set; }
    public string password { get; set; }
    public string LoginToken { get; set; }
}

public class RootObject
{
    public Data data { get; set; }
}

and in your post method

public string Post([FromBody]RootObject data)

Now you even don't have to deserialise it. and can access direct as property of class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM