Stefano Caporale
Stefano Caporale

Reputation: 21

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

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?

Upvotes: 2

Views: 3719

Answers (1)

nozzleman
nozzleman

Reputation: 9649

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?

Upvotes: 6

Related Questions