如何从动态变量中读取,ValueKind=Array

huangapple go评论67阅读模式
英文:

How to read from Dynamic variable, ValueKind=Array

问题

我得到了一个动态变量,它将自己列为ValueKind=Array,并且我可以看到其中有一些字符串:

["a", "b"]...

我是从以下地方获取的:

Dictionary<string, dynamic?> dictionary = 
  System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, dynamic>>(response);
if (dictionary.TryGetValue("memberList", out dynamic? value))
  // 这里就是"value"

我该如何从中读取?

我在这里提问,因为谷歌会找到有关数组和动态变量以及动态数组的任何信息,但不会找到有关这个主题的信息。

英文:

I get a dynamic variable, which lists itself as ValueKind=Array, and I can see some strings in there as

["a", "b"]...

I get it from:

Dictionary<string, dynamic?> dictionary = 
  System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, dynamic>>(response);
if (dictionary.TryGetValue("memberList", out dynamic? value))
  // here this is the "value"

How do I read from that?

I ask here, as google will find anything on Arrays and Dynamic and Dynamic arrays, but not on this subject

答案1

得分: 2

如果您知道它将是一个数组,您可以将其视为一个数组,但智能感知不能帮助您,因为它不知道它将是什么类型。

例如,如果 dynamic 是一个数组,那么这将起作用:

var myListVariable = myDynamicVariable.ToList();

[编辑:]

但是,根据上面的评论,它看起来是一个 JSON 数组,所以您可以使用类似以下的方式:

var yourStringList = JsonSerializer.Deserialize<List<string>>(yourDynamicObject);

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#824-the-dynamic-type

英文:

If you know it will be an array, you can just treat it as an array, but intellisense cannot help you, because it doesn't know what type it will be.

For example, this would work, if the dynamic is an array:

var myListVariable = myDynamicVariable.ToList();

[edit:]

But, as per a comment above, it looks like it is a json array, so you would use something like this:

var yourStringList = JsonSerializer.Deserialize&lt;List&lt;string&gt;&gt;(yourDynamicObject);

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#824-the-dynamic-type

huangapple
  • 本文由 发表于 2023年6月19日 22:46:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76507735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定