Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 215
Nick Avatar asked Aug 28 '19 22:08

Nick


People also ask

What is JSON text JSON?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

How do I deserialize text JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is Deserializing JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

How does JsonSerializer deserialize work?

Deserialize(Utf8JsonReader, Type, JsonSerializerOptions) Reads one JSON value (including objects or arrays) from the provided reader and converts it into an instance of a specified type.


1 Answers

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.

like image 110
IronMan Avatar answered Sep 20 '22 05:09

IronMan