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
Since you are using
dynamic
all subsequent variables are resolved asdynamic
too. Just declare one of the types (for examplestring
for serialization result) and use indexer +GetValue
: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
and you can create a json string much more simple way and without using options too