在C#中从Web检索匿名类型

Sat*_*nix 9 c# xml json

我正在尝试从网上检索一些数据.数据以JSON对象或XML形式提供:在这两种情况下,我都不想基于XML/JSON的结构构建模型,而只是检索我需要的数据.

HttpResponseMessage response = await client.PostAsync(
"http://www.someAPI.com/api.xml",
requestContent);

response.EnsureSuccessStatusCode();

HttpContent content = response.Content;
Run Code Online (Sandbox Code Playgroud)

如果我必须根据我将收到的数据结构构建模型,我会这样做:我只是想知道是否有任何替代方案.我可以解析content为匿名类型,并将数据检索为任意字段或属性或数组索引吗?

让我们说:response.Countries[5].CountryId.是否有可能在这两种类型(JSON和XML)中的任何一种?我该怎么做?

Sam*_*ngh 19

编辑#2:

我在下面添加了一个关于使用优秀的Json.NET库反序列化为dynamic对象的说明.


编辑#1:

感谢Hoghweed的回答,我的答案现在更完整了.具体来说,我们要HttpContent,我们从中获取HttpResponseMessage.ContentExpandoObject为了使dynamic-ness按预期方式工作:

dynamic content = response.Content.ReadAsAsync<ExpandoObject>().Result;
var myPropertyValue = content.MyProperty;
Run Code Online (Sandbox Code Playgroud)

为了获得ReadAsync<T>()扩展方法,你需要使用NuGetSystem.Net.Http.Formatting.dllMicrosoft.AspNet.WebApi.Client包中下载和安装(这里是"旧的"Nuget页面,它提到它现在包含在上面的包中).


原答案:

因此,您不希望创建POCO并且必须将其属性作为XML/JSON结构进行管理,以便进行更改.dynamic对你的用例来说似乎很完美:

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)
Run Code Online (Sandbox Code Playgroud)

特别是关于XML:你可以尝试Anoop Madhusudanan的ElasticObject之间进行转换时,这可能是非常有益的dynamicXML,和背部.

特别是关于JSON:你可以使用 Json.NET做这样的事情:

dynamic content = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
var myPropertyValue = content.MyProperty;
Run Code Online (Sandbox Code Playgroud)

最重要的是你不会依赖于Microsoft.AspNet.WebApi.Client包(因为它v4.0.30506.0取决于Json.NET).缺点是您将无法将其用于XML.

希望这可以帮助.