title: How do I get System.Text.Json to deserialize objects into their original type?
body: <p>I'm working with a POCO class in .NET 5.0 that I need to serialize and deserialize to and from the browser, and this is in a library where I don't want to have to tell the users which serializers they must use.</p>
  <p>So I'm trying to make it work with both Newtonsoft.Json and System.Text.Json.</p>
  <p>My problem is that values stored in fields with type object aren't being deserialized into their original type, in System.Text.Json.</p>
  <pre><code>using Shouldly;
  using Xunit;
  using SJ = System.Text.Json;
  using NJ = Newtonsoft.Json;
  
  public class SerializationTests
  {
      [Fact]
      public void TestNJ()
      {
          var nvp = new NVP { Name = &quot;a name&quot;, Value = &quot;a value&quot; };
  
          var s = NJ.JsonConvert.SerializeObject(nvp);
          var d = NJ.JsonConvert.DeserializeObject&lt;NVP&gt;(s);
          d.ShouldBeEquivalentTo(nvp);
      }
  
      [Fact]
      public void TestSJ()
      {
          var nvp = new NVP { Name = &quot;a name&quot;, Value = &quot;a value&quot; };
  
          var s = SJ.JsonSerializer.Serialize(nvp);
          var d = SJ.JsonSerializer.Deserialize&lt;NVP&gt;(s);
          d.ShouldBeEquivalentTo(nvp);
      }
  }
  </code></pre>
  <p>TestNJ passes.</p>
  <p>TestSJ throws an exception:</p>
  <blockquote>
  <p>Expected value to be System.String but was System.Text.Json.JsonElement'</p>
  </blockquote>
  <p>In the debugger it's clear what's going on.</p>
  <p>In both TestNJ() and TestSJ(), at the beginning, <code>nvp</code> has the value:</p>
  <pre><code>nvp: {NVP}
    Name [string]: &quot;a name&quot;
    Value [object]: &quot; a value&quot;
  </code></pre>
  <p>In both, after serialization, <code>s</code> has the value I'd expect:</p>
  <pre><code>&quot;{\&quot;Name\&quot;:\&quot;a name\&quot;,\&quot;Value\&quot;:\&quot;a value\&quot;}&quot;
  </code></pre>
  <p>But where in TestNJ(), after deserialization, <code>d</code> has the value:</p>
  <pre><code>d: {NVP}
    Name [string]: &quot;a name&quot;
    Value [object]: &quot; a value&quot;
  </code></pre>
  <p>In TestSJ(), <code>d</code> has the value:</p>
  <pre><code>d: {NVP}
    Name [string]: &quot;a name&quot;
    Value [object]: ValueKind = String: &quot;a value&quot;
  </code></pre>
  <p>What is going on here? How do I get System.Text.Json to actually deserialize this type?</p>