json 将JToken内容初始化为Object

1qczuiv0  于 2023-10-21  发布在  其他
关注(0)|答案(2)|浏览(168)

我想将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());
iqjalb3h

iqjalb3h1#

可以使用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数组,没有任何问题。

hsgswve4

hsgswve42#

--这对我来说很有效,Json是超级巨大的+111000行-

//String of keys to search deepin the Json for the desired 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);   //Get a JObject from the Json
// Find the desired tree branch by the token keys
var partitionsJObject = data.SelectToken(sTokenKeys).ToList();
// get the array of JTokens and serialize-deserialize into 
// appropriate object 
var partitions = JsonConvert.DeserializeObject<List<Partition>>(JsonConvert.SerializeObject(partitionsJObject));

//now i can read the List<Partition>> partitions object for the 
// values im looking for

相关问题