将JToken内容反序列化为对象

时间:2015-02-13 03:41:21

标签: c# json salesforce json.net asp.net-web-api2

我想将JToken内容反序列化为对象(User)。我怎么能这样做?

这是我的json字符串:

string json = @"[{""UserId"":0,""Username"":""jj.stranger"",""FirstName"":""JJ"",""LastName"":""stranger""}]";

将其作为JToken发送到api参数。

用户类:

public class user
{
    public int UserId {get; set;}
    public string Username {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

Web Api方法:

public IHttpActionResult Post([FromBody]JToken users)
{
       UserModel.SaveUser(users);
       //...
}

Salesforce中的API调用:

string json = '[{"UserId":0,"Username":"jj.stranger","FirstName":"JJ","LastName":"stranger"}];
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();

req.setEndpoint('test.com/api/UserManagement');
req.setMethod('POST');
req.setBody(json);
req.setHeader('Content-Type', 'application/json');

try {
    res = http.send(req);
} catch(System.CalloutException e) {
    System.debug('Callout error:' + e);
}

System.debug(res.getBody());

1 个答案:

答案 0 :(得分:43)

您可以使用JToken.ToObject泛型方法。     http://www.nudoq.org/#!/Packages/Newtonsoft.Json/Newtonsoft.Json/JToken/M/ToObject(T)

服务器API代码:

 public void Test(JToken users)
 {
     var usersArray = users.ToObject<User[]>();
 }

这是我使用的客户端代码。

string json = "[{\"UserId\":0,\"Username\":\"jj.stranger\",\"FirstName\":\"JJ\",\"LastName\":\"stranger\"}]";
HttpClient client = new HttpClient();
var result = client.PostAsync(@"http://localhost:50577/api/values/test", new StringContent(json, Encoding.UTF8, "application/json")).Result;

对象转换为Users数组没有任何问题。