简体   繁体   English

如何在C#中使用RestSharp反序列化动态json属性?

[英]How I deserialize a dynamic json property with RestSharp in C#?

I have a web service (I can't edit) with this structure: 我有一个具有以下结构的Web服务(我无法编辑):

/users /用户

{
    "response" : {
        "users": [{"name": "John"},{"name": "Jack"}]
    },
    "page" : { "current":1, "total":1}
}

/pets /宠物

{
    "response" : {
        "pets": [{"name": "Fido"},{"name": "Tweety"}]
    },
    "page" : { "current":1, "total":1}
}

As you can see the property name in the "response" property changes. 如您所见,“响应”属性中的属性名称已更改。 How can deserialize a generic response with RestSharp? 如何使用RestSharp反序列化一般响应? I don't want to write a Response class for every resource. 我不想为每个资源编写一个Response类。

I have written the following generic Response class 我编写了以下通用Response类

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;} }

Of course RestSharp can't link the dynamic json property with the ResponseBody.list attribute. 当然,RestSharp无法将动态json属性与ResponseBody.list属性链接。 How can I do this? 我怎样才能做到这一点?

I'll start with saying that is not elegant at all: 我首先要说一点都不优雅:

You can get the raw JSON response using 您可以使用获取原始的JSON响应

RestResponse response = client.Execute(request);
var jsonString = response.Content; // raw content as string

From there on, you can query it using JSON.NET like that: 从那里开始,您可以像这样使用JSON.NET查询它:

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 would then hold a list of your names. resources将保存您的姓名列表。 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? 它的可读性更高,您的响应对象可能不会全部只有一个属性,对吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM