5

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

2
  • 1
    You could just use NewtonSoft.Json in .NET 6, too. Commented Dec 16, 2021 at 11:42
  • Oh, --- that is a good point... I have been asked "just to use the framework's one", hence my question, but indeed. Commented Dec 16, 2021 at 14:53

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Keep in mind, as nvoigt mentioned, you can still use NewtonSoft; for me this was just a project requirement.
You can also chain the .GetProperty() methods if you have nested JSON, example: .GetProperty("contents").GetProperty("quotes")[0].GetProperty("quote").GetString()
2

Just in case someone else comes across this while searching on the subject...

If you parse as a JSON node directly, you can get your data in a single GetValue.

Example (using explicit types for clarity and '!' to handle nulls):

JsonNode? jnode = JsonNode.Parse(jsonString);
string quote = jnode["contents"]!["quotes"]!.AsArray()[0]!["quote"]!.GetValue<string>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.