0

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.

Mohammad Miras
  • 143
  • 1
  • 9
  • In debug mode, if you looked into the deserializedToken, what does it look like? Your dynamic object is seen as a dictionary by the serializer. – Anand Sowmithiran Dec 24 '22 at 08:40

2 Answers2

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>();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

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);
Serge
  • 40,935
  • 4
  • 18
  • 45