Home > Back-end >  Dynamic retrieve json element .NET 6
Dynamic retrieve json element .NET 6

Time:12-19

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

CodePudding user response:

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.

  • Related