【问题标题】:How to convert JArray to KeyValuePair structure in C#?如何在 C# 中将 JArray 转换为 KeyValuePair 结构?
【发布时间】:2017-05-07 16:30:27
【问题描述】:

我有一个带有对象的 JArray 有两个属性。例如:

[
     {"Prop1":"key1", "Prop2":"value1"}, 
     {"Prop1":"key2", "Prop2":"value2"}, 
     {"Prop1":"key3", "Prop2":"value3"}
]

而且我需要 C# 中的 KeyValuePair(或 Dictionary 无关紧要)结构,例如

key1-value1
key2-value2
key3-value3

Prop1 和 Prop2 的名称也可以更改,这意味着 JArray 可以有不同的道具名称,但对象中的属性数始终为 2。因此我需要将 JArray 反序列化为 List<KeyValuePair> 的通用方法。

【问题讨论】:

    标签: c# json json.net deserialization


    【解决方案1】:

    给定一个JArray 类型的变量array,您可以使用System.Linq 命名空间中的extension 方法执行以下操作:

    var pairs = array
        // Cast array items from JToken to JObject.  
        // You could filter instead using `OfType<JObject>() if nulls might be present
        .Cast<JObject>()
        // Convert the first and second property values to a KeyValuePair
        .Select(o => new KeyValuePair<string, string>((string)o.PropertyValues().ElementAtOrDefault(0), 
                                                      (string)o.PropertyValues().ElementAtOrDefault(1)))
        .ToList();
    
    var dict = pairs.ToDictionary(p => p.Key, p => p.Value);
    

    示例fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 2017-02-09
      • 2014-04-24
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多