Home > Enterprise >  How to read values from JsonNode in System.Text.Json
How to read values from JsonNode in System.Text.Json

Time:12-25

I want to serialize a refresh token and send it to the client.

Then on return, I want to deserialize and read it.

Here's my code.

using System.Text.Json;
using System.Dynamic;
using System;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Text.Json.Nodes;


dynamic token = new ExpandoObject();

token.UserName = "John";
token.Expires = DateTime.Now.AddMinutes(5);
token.CreateDate = DateTime.Now;

var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
                };

var refreshToken = JsonSerializer.Serialize(token,  options);

Console.WriteLine(refreshToken);

var deserializedToken = JsonSerializer.Deserialize<JsonNode>(refreshToken, options);

var userName = "How can I extract username from JsonNode";

I tried to use JsonNode["UserName"].Value, but it does not work.

CodePudding user response:

Since you are using dynamic all subsequent variables are resolved as dynamic too. Just declare one of the types (for example string for serialization result) and use indexer GetValue:

string refreshToken = JsonSerializer.Serialize(token,  options);

JsonNode? deserializedToken = JsonSerializer.Deserialize<JsonNode>(refreshToken, options);
var userName = deserializedToken["userName"].GetValue<string>();

CodePudding user response:

Your type after deserializaton will be a JsonNode, If you try to use a dynamic, your type after deserialization will be a JsonElement, so you can not gain anything with dynamic too. You can just use Parse

JsonNode deserializedToken = JsonNode.Parse(refreshToken);
string userName = (string) deserializedToken["userName"];

and you can create a json string much more simple way and without using options too

    var token = new
    {
        userName = "John",
        expires = DateTime.Now.AddMinutes(5),
        createDate = DateTime.Now
    };

string refreshToken = System.Text.Json.JsonSerializer.Serialize(token);
  • Related