Retrieve anonymous type from the web in C#
c#, json, xml
Solution
EDIT #2:
I've added a note below about using the excellent Json.NET library to deserialize to a `dynamic` object.
EDIT #1:
Thanks to Hoghweed's answer, my answer below is now more complete. Specifically, we need to cast the `HttpContent` we get from `HttpResponseMessage.Content` to `ExpandoObject` in order for the `dynamic`-ness to work as expected:
dynamic content = response.Content.ReadAsAsync<ExpandoObject>().Result;
var myPropertyValue = content.MyProperty;
To get the `ReadAsync<T>()` extension method though, you'd need to use NuGet to download and install `System.Net.Http.Formatting.dll` from the `Microsoft.AspNet.WebApi.Client` package (here's the "old" Nuget page, which mentions that it is now included in the above package).
Original Answer:
So, you don't want to have to create a POCO and have to manage its properties as the XML/JSON structure you get back changes. `dynamic` seems perfect for your use case:
HttpResponseMessage response = await client.PostAsync(
"http://www.someAPI.com/api.xml", requestContent);
response.EnsureSuccessStatusCode();
dynamic content = response.Content.ReadAsAsync<ExpandoObject>().Result; // Notice the use of the dynamic keyword
var myPropertyValue = content.MyProperty; // Compiles just fine, retrieves the value of this at runtime (as long as it exists, of course)
Specifically regarding XML: you could try Anoop Madhusudanan's `ElasticObject` which might be very helpful when converting between `dynamic` and `XML`, and back.
Specifically regarding JSON: you could use Json.NET do something like this:
dynamic content = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
var myPropertyValue = content.MyProperty;
The up-side is that you won't take a dependency on the `Microsoft.AspNet.WebApi.Client` package (which, as of `v4.0.30506.0`, depends on Json.NET). The downside is that you won't be able to use this for XML.
Hope this helps.
Problem
I'm trying to retrieve some data from the web. The data is served either as JSON object or XML: in both cases I'd like not to build a model based on the structure of this XML/JSON but to just retrieve the data I need. ``` HttpResponseMessage response = await client.PostAsync( "http://www.someAPI.com/api.xml", requestContent); response.EnsureSuccessStatusCode(); HttpContent content = response.Content; ``` If I have to build a model based on the data structure I'll receive back I'll do it: I just want to know if there is any alternative. Can I parse `content` as an anonymous type and, say, retrieve the data as arbitrary fields or properties or array indexes? Let's say: `response.Countries[5].CountryId`. Is it possible in any of these 2 types (JSON and XML)? How can I do it?