2

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?

0

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! It seems Object can be a list or a single object!
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.