Get System.Object from System.Text.Json.JsonElement

41 views Asked by At

I am using the var myObject = await JsonSerializer.DeserializeAsync<MyObject>(stream); to deserialize a Json file into my object structure.

public class MyObject
{
   public string Name { get; set; }
   public object SomeObject { get; set; } // I don't know the type
}

The challenge is that SomeObject is an object. That means that it becomes a System.Text.Json.JsonElement. But I would like to have the real value instaed.

So instead of

  • { SomeObject: "MyString" } is now a JsonElement ValueKind = String : "MyString" but I would like to have a System.String "MyString"
  • { SomeObject: 123 } is now a JsonElement ValueKind = Number : "123" but I would like to have a System.Int32 123

So my question: How to make sure that the value is always converted to its real type?

0

There are 0 answers