![](/img/trans.png)
[英]How can I Read Dynamic String and Store each key string Value into a varaible?
[英]How can I read each key values
我正在閱讀下面的成本值
原始數據如下:-
{ "Key":"Cost", "Value":[ { "Key":"a", "Value":5.25 }, { "Key":"b", "Value":0 }, { "Key":"c", "Value":5.25 }, { "Key":"d", "Value":0 } ] }
我的預期結果是我需要讀取 a,b,c,d 而不是數據 [“Cost”]。
我怎樣才能分別閱讀
// Root myDeserializedClass = JsonSerializer.Deserialize<Root>(myJsonResponse);
//myDeserializedClass.Value will contain all key and value
public class Root
{
[JsonPropertyName("Key")]
public string Key { get; set; }
[JsonPropertyName("Value")]
public List<Value> Value { get; set; }
}
public class Value
{
[JsonPropertyName("Key")]
public string Key { get; set; }
[JsonPropertyName("Value")]
public double Value { get; set; }
}
通過https://json2csharp.com/生成的類
最簡單的方法是將 json 轉換為字典
var costs= JObject.Parse(json)["Value"]
.ToDictionary(j => (string) j["Key"], j=> (decimal) j["Value"] );
decimal c = costs["c"]; //5.25
或使用動態
var dict = JObject.Parse(json)["Value"]
.ToDictionary(j => (string)j["Key"], j => (object)j["Value"]);
dynamic costs = dict.Aggregate(new ExpandoObject() as IDictionary<string, object>,
(a, p) => { a.Add(p); return a; });
decimal c = costs.c;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.