简体   繁体   English

如何将匿名类型与 LINQ 结合到 JSON?

[英]How can i combine anonymous types with LINQ to JSON?

consider the following json file考虑以下 json 文件

{
  "test": {
    "CR": {
     "name": "Car"
    },
    "BK": {
     "name": "Bike"
    }
}

How can i combine usage of anonymous types with LINQ to JSON for creating key-value pairs of我如何结合使用匿名类型与 LINQ 到 JSON 来创建键值对

    CR Car
    BK Bike

by using LINQ to JSON?通过使用 LINQ 到 JSON?

I have tried something as simple as the following for start, but it does not even compile我已经尝试过像下面这样简单的开始,但它甚至没有编译

    JObject o = JObject.Parse(s);
    var pairs = o["test"].Select(x => x.Value).ToList();

To be more precise something like this pseudocode更准确地说,像这个伪代码

var pairs = o["test"].Select( new { key = x => x.firstOrDefault().Name, value = x => x.Value}).ToList();

Rather than creating a runtime anonymous type with variable property names, you could use LINQ to JSON to create a restructured JObject like so:您可以使用LINQ 到 JSON来创建重组的JObject ,而不是创建具有变量属性名称的运行时匿名类型,如下所示:

var pairs = new JObject( ((JObject)o["test"])
                        .Properties()
                        .Select(p => new JProperty(p.Name, p.Value["name"])) );

Or, if you would prefer a Dictionary<string, string> , you may do:或者,如果您更喜欢Dictionary<string, string> ,您可以这样做:

var dictionary = ((JObject)o["test"]).Properties()
    .ToDictionary(p => p.Name, p => (string)p.Value["name"]);

Or an ExpandoObject :ExpandoObject

var expando = new ExpandoObject();
foreach (var p in ((JObject)o["test"]).Properties())
{
    IDictionary<string, object> d = expando;
    d.Add(p.Name, (string)p.Value["name"]);
}

Creating a run-time anonymous type using property names defined by a dictionary is nontrivial as it requires runtime code generation.使用字典定义的属性名称创建运行时匿名类型并非易事,因为它需要生成运行时代码。 If you really need this, see C# anonymous object with properties from dictionary .如果你真的需要这个,请参阅C# 匿名 object 与字典属性

Demo fiddle here .演示小提琴在这里

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

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