Search code examples
c#json.net.net-6.0

Dynamic retrieve json element .NET 6


I want to retrieve a single value from a json string.

Previously I used Newtonsoft like this:

var jsonString = @"{ ""MyProp"" : 5 }";
dynamic obj = Newtonsoft.Json.Linq.JObject.Parse(jsonString);
        
Console.WriteLine(obj["MyProp"].ToString());

But I can't seem to get it to work in .NET 6:

I've tried this so far:

var jsonString = @"{ ""MyProp"" : 5 }";
dynamic obj = await System.Text.Json.JsonSerializer.Deserialize<dynamic>(jsonString);
        
Console.WriteLine(obj.MyProp.ToString());

which results in this error:

Unhandled exception. Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Text.Json.JsonElement.this[int]' has some invalid arguments


Solution

  • Reading upon this github, I had success using this approach:

    NET 6 will include the JsonNode type which can be used to serialize and deserialize dynamic data.

    Trying it results in:

    using System;
                        
    public class Program
    {
        public static void Main()
        {
            var jsonString = @"{ ""MyProp"" : 5 }";
            //parse it
            var myObject = System.Text.Json.JsonDocument.Parse(jsonString);
            //retrieve the value
            var myProp= myObject.RootElement
                                .GetProperty("MyProp");
            
            Console.WriteLine(myProp);
        }
    }
    

    Which seems to work in my case.


    As by @robnick's comment - you can also chain GetProperty to get nested properties of the data structure.

    var quote = rootElement.GetProperty("contents")
                           .GetProperty("quotes")[0]
                           .GetProperty("quote")
                           .GetString();