我想将 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/#!/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 数组。
//String of keys to search deep down in the Json for the json objects
public string sTokenKeys = "results.drug.drugsfda.partitions";
//Read the download.json file into its objects.
StreamReader reader = new StreamReader(JsonFileLocation);
var json = reader.ReadToEnd();
var data = JObject.Parse(json);
var partitionsJObject = data.SelectToken(sTokenKeys).ToList();
var partitions = JsonConvert.DeserializeObject<List<Partition>>(JsonConvert.SerializeObject(partitionsJObject));