Search code examples
c#.net-coresystem.text.json

How do you read a simple value out of some json using System.Text.Json?


I have this json

{"id":"48e86841-f62c-42c9-ae20-b54ba8c35d6d"}

How do I get the 48e86841-f62c-42c9-ae20-b54ba8c35d6d out of it? All examples I can find show to do something like

var o = System.Text.Json.JsonSerializer.Deserialize<some-type>(json);
o.id // <- here's the ID!

But I don't have a type that fits this definition and I don't want to create one. I've tried deserializing to dynamic but I was unable to get that working.

var result = System.Text.Json.JsonSerializer.Deserialize<dynamic>(json);
result.id // <-- An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Linq.Expressions.dll but was not handled in user code: ''System.Text.Json.JsonElement' does not contain a definition for 'id''

Can anyone give any suggestions?


edit:

I just figured out I can do this:

Guid id = System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("id").GetGuid();

This does work - but is there a better way?


Solution

  • you can deserialize to a Dictionary:

    var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(json)
    

    Or just deserialize to Object which will yield a JsonElement that you can call GetProperty on.