skip to Main Content

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.

2

Answers


  1. 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>();
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search