I see two issues, preventing the code to work:
The syntax of your jsonObject declaration is not correct. Declare it as a string and inside the string use the escape "backslash + double quote" for every double quote:
var jsonObject = "{\"att1\": \"val1\",\"att2\": \"val2\",\"att3\": \"val3\",\"att4\": \"val4\"}";
Then, when using Newtonsoft.Json.Converters
, instead of List<ExpandoObject>
it needs to be ExpandoObject
in the type argument, because an ExpandoObject is inside already a dictionary (not a list):
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(jsonObject, expConverter);
The following code fixes the two issues mentioned above and displays the key/value pairs on screen:
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
void Main()
{
// 1. this needs to be a string
var jsonObject =
"{\"att1\": \"val1\",\"att2\": \"val2\",\"att3\": \"val3\",\"att4\": \"val4\"}";
var expConverter = new ExpandoObjectConverter();
// 2. the correct type argument is ExpandoObject
dynamic obj =
JsonConvert.DeserializeObject<ExpandoObject>(jsonObject, expConverter);
// display the keys and values on screen
foreach (var o in obj)
{
Console.WriteLine($"{o.Key}, {o.Value}");
}
}
The output is:
att1, val1
att2, val2
att3, val3
att4, val4
Note: You can easily convert the expando to a dictionary (internally it already is an IDictionary
) like:
var dict = new Dictionary<string, object>(obj);
That allows to do a dict.Dump()
in LinqPad (not supported with ExpandoObject)
If you're trying it out in LinqPad press F4 and add the NUGET package Json.NET
(if you don't have the paid version of LinqPad, NUGET function is limited there - try Rock.Core.Newtonsoft
in this case).
dynamic
. Just typecast the whole thing toList<ExpandoObject>
– Walkerwalkietalkiedynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(jsonObject, expConverter);
works just fine... – Milden