如何在C#中使用RestSharp反序列化动态json属性? [英] How I deserialize a dynamic json property with RestSharp in C#?
问题描述
我有一个具有以下结构的Web服务(我无法编辑):
I have a web service (I can't edit) with this structure:
/用户
{
"response" : {
"users": [{"name": "John"},{"name": "Jack"}]
},
"page" : { "current":1, "total":1}
}
/宠物
{
"response" : {
"pets": [{"name": "Fido"},{"name": "Tweety"}]
},
"page" : { "current":1, "total":1}
}
如您所见,响应"属性中的属性名称已更改. 如何使用RestSharp反序列化一般响应?我不想为每种资源编写一个Response类.
As you can see the property name in the "response" property changes. How can deserialize a generic response with RestSharp? I don't want to write a Response class for every resource.
我编写了以下通用Response类
I have written the following generic Response class
class RestResponse{
public ResponseBody response { get; set; }
public ResponsePage page { get; set; }
}
class ResponseBody {
public List<dynamic> resourceList { get; set; }
}
class ResponsePage {
public int current { get; set; }
public int total { get; set; }
}
class User { public string name {get; set;} }
class Pet { public string name {get; set;} }
当然,RestSharp无法将动态json属性与ResponseBody.list属性链接. 我该怎么办?
Of course RestSharp can't link the dynamic json property with the ResponseBody.list attribute. How can I do this?
推荐答案
我首先要说一点都不优雅:
I'll start with saying that is not elegant at all:
您可以使用
RestResponse response = client.Execute(request);
var jsonString = response.Content; // raw content as string
从那里开始,您可以使用 JSON.NET 对其进行查询像这样:
From there on, you can query it using JSON.NET like that:
var jObject = JObject.Parse(jsonString);
// this could probably be written nicer, but you get the idea...
var resources = jObject ["response"]["users"].Select(t => t["name"]);
然后
resources
将保存您的姓名列表.这是丑陋的,不灵活的,我不建议这样做.
resources
would then hold a list of your names. This is ugly, inflexible, and I wouldn't recommend it.
更好地坚持巧妙的继承和自定义类.它更具可读性,您的响应对象可能不仅会全部具有一个属性,对吗?
Better stick with clever inheritance and custom classes. Its much more readable and your response object will probably not all only have one property, right?
这篇关于如何在C#中使用RestSharp反序列化动态json属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!