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

南笙酒味 提交于 2019-12-22 21:36:59

问题


I have a web service (I can't edit) with this structure:

/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? I don't want to write a Response class for every resource.

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

Of course RestSharp can't link the dynamic json property with the ResponseBody.list attribute. How can I do this?


回答1:


I'll start with saying that is not elegant at all:

You can get the raw JSON response using

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:

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. 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?



来源:https://stackoverflow.com/questions/32478208/how-i-deserialize-a-dynamic-json-property-with-restsharp-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!