简体   繁体   English

在ASP.net C#中从JSON检索数组

[英]Retrieving an array from JSON in ASP.net C#

I'm gathering data from a web API which returns a complex JSON string. 我正在从Web API收集数据,该Web API返回复杂的JSON字符串。 This contains values of many different types, a few arrays, and some fairly deep nesting. 它包含许多不同类型的值,一些数组和一些相当深的嵌套。

Currently I'm converting the string to a dynamic object like so: 目前,我正在将字符串转换为动态对象,如下所示:

dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);

Then I'm retrieving values from this object as needed and typecasting them, however this method gives a null reference exception when I attempt to retrieve an array: 然后,根据需要从该对象中检索值并进行类型转换,但是当我尝试检索数组时,此方法给出了空引用异常:

int myValue         = (int)dynamicObject.foo.value; // Works!
int[] myArrayOfInts = (int[])dynamicObject.bar.values; // Null

I'm not sure how to proceed as I'm fairly new to C# and ASP.net. 由于我对C#和ASP.net相当陌生,因此我不确定该如何进行。 Most of the solutions I have come across so far require the creation of small, strictly-typed classes which mirror the entire JSON structure. 到目前为止,我遇到的大多数解决方案都需要创建小型的,类型严格的类,这些类反映整个JSON结构。 In my case it would be preferable to simply use a dynamic object, partly for simplicity and partly because only certain values are actually being used. 就我而言,最好使用一个动态对象,部分是为了简单起见,部分是因为实际上只使用了某些值。

When I try to run your code, I get a RuntimeBinderException: Cannot convert type 'Newtonsoft.Json.Linq.JArray' to 'int[]' . 当我尝试运行您的代码时,出现RuntimeBinderException: Cannot convert type 'Newtonsoft.Json.Linq.JArray' to 'int[]' You can do this conversion with ToObject . 您可以使用ToObject进行此转换。

dynamic dynamicObject = JsonConvert.DeserializeObject("{\"values\": [1, 3, 4]}");
int[] myArrayOfInts = dynamicObject.values.ToObject<int[]>();

The cast to int works because a casting conversion is defined for many types including int , but not int[] . 强制转换为int之所以有效,是因为为许多类型(包括int )定义了强制转换,但int[]却没有。

You could deserialize the array using the ToObject<type> extension method (where type is the desired data type): 您可以使用ToObject<type>扩展方法(其中type是所需的数据类型)反序列化数组:

var jsonString = @"{ ""name"":""test"", ""array"": [""10"",""20"",""30"",""40""] }";
dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
Console.WriteLine(((string)dynamicObject.name));
var items = dynamicObject.array.ToObject<int[]>();
foreach (var item in items)
{
    Console.WriteLine(item);
}

The output is: 输出为:

test
10
20
30
40

Another possibility would be to cast the object to JObject and then fetch the array as a property - the retrieved object is automatically of type JToken , which allows iteration: 另一种可能性是将对象JObjectJObject ,然后将数组作为属性获取-检索到的对象自动为JToken类型,从而允许迭代:

var array = ((JObject)dynamicObject)["array"];
foreach (var item in array)
{
    Console.WriteLine(item.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM