Search code examples
c#jsonlinqjson.netlinq-to-json

How can i combine anonymous types with LINQ to JSON?


consider the following json file

{
  "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

    CR Car
    BK Bike

by using LINQ to 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();

Solution

  • Rather than creating a runtime anonymous type with variable property names, you could use LINQ to JSON to create a restructured JObject like so:

    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:

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

    Or an 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.

    Demo fiddle here.