BrunoMartinsPro
BrunoMartinsPro

Reputation: 1856

Deserializing with JSON.net dynamically

I have a transparent proxy that tunels the requests between the frontoffice and the backoffice, my transparent proxy has 4 methods(GET,POST,PUT,DELETE) that makes requests to several services dynamically.
My problem is that i cannot deserialize a list or an object depending on the response.

One Object:

var client = new WebClient { UseDefaultCredentials = true };
client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
var result = JsonConvert.DeserializeObject<Dictionary<String, Object>>(Encoding.UTF8.GetString(client.DownloadData(ConfigurationManager.AppSettings["InternalWebApiUrl"] + "/" + url)));

return Request.CreateResponse(result);

List of Objects

var client = new WebClient { UseDefaultCredentials = true };
client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
var result = JsonConvert.DeserializeObject<List<Object>>(Encoding.UTF8.GetString(client.DownloadData(ConfigurationManager.AppSettings["InternalWebApiUrl"] + "/" + url)));

return Request.CreateResponse(result);

Is there any way to verify if the response is an array or just one object?

Upvotes: 2

Views: 6329

Answers (2)

Danimt
Danimt

Reputation: 1067

Try this!

var client = new WebClient { UseDefaultCredentials = true };

client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
var result = JsonConvert.DeserializeObject<Object>(Encoding.UTF8.GetString(client.DownloadData(ConfigurationManager.AppSettings["InternalWebApiUrl"] + "/" + url)));

return Request.CreateResponse(result);

Upvotes: 2

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

You could parse the JSON using JToken.Parse first, and then determine what you're dealing with:

JToken token = JToken.Parse(json);

if (token.Type == JTokenType.Object)
{
    Dictionary<string, object> d = token.ToObject<Dictionary<string, object>>();
}
else if (token.Type == JTokenType.Array)
{
    List<object> list = token.ToObject<List<object>>();
}

Alternatively if you don't actually care what you're working with, you could use the JToken.

Upvotes: 2

Related Questions