我想将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());
您可以使用JToken.ToObject泛型方法。http://www.nudoq.org/#/软件包/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数组,没有任何问题。