我想解析以下JSON响应:
{
"message": "string",
"errorCode": "string",
"totalSize": 0,
"offset": 0,
"done": true,
"nextRecordsUrl": "string",
"records": [
{
"id": "string",
"name": "string",
"external_ID_vod__c": "string",
"vExternal_Id_vod__c": "string"
}
]
}
**请注意,有多个“记录”
我用于反序列化JSON响应的相关类是:
public class RecordProduct
{
public string id { get; set; }
public string name { get; set; }
public string external_ID_vod__c { get; set; }
public string vExternal_Id_vod__c { get; set; }
}
public class Products
{
public string message { get; set; }
public string errorCode { get; set; }
public int totalSize { get; set; }
public int offset { get; set; }
public bool done { get; set; }
public string nextRecordsUrl { get; set; }
public List<RecordProduct> records { get; set; }
}
正在调用API的代码:
public void getAllProductInfo()
{
RestClient client = new RestClient("blahblahblah/");
RestRequest request = new RestRequest("/api/Products", Method.GET);
string securityToken = getBearerToken();
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", "Bearer " + securityToken);
IRestResponse<JsonResponseSetup.Datum.Products> response = client.Execute<JsonResponseSetup.Datum.Products>(request);
var res = response.Data.records;
res.ForEach(Console.WriteLine);
}
当我执行最后一行时:res.ForEach(Console.WriteLine);
我没有得到要打印的记录。
修改:我想通了。我只是错误地访问了记录的成员。 以下内容代替了我代码的最后两行。
foreach(var item in response.Data.records)
{
Console.WriteLine($"name: {item.name}, id: {item.id}");
}
答案 0 :(得分:0)
Newtonsoft是一个易于使用的框架,可帮助您在.NET和JSON对象之间进行转换,如文档中的this example所示。
简而言之,您只需将JSON传递给DeserializeObject
方法,然后指定对应的JSON应该解析到的类。
答案 1 :(得分:0)
尝试一下
Products facebookFriends = new JavaScriptSerializer().Deserialize<Products>(result);