In .NET Core 3.1 I use System.Text.Json.JsonSerializer
to handle my Json objects. When I tried to write an error case when the JsonSerializer.Deserialize<T>()
gets a Json string that is of a different type than T
I don't get any exception.
Here is a sample code:
using System;
using System.Text.Json;
namespace JsonParsing
{
class Program
{
{
try
{
B b = JsonSerializer.Deserialize<B>( JsonSerializer.Serialize( new A() { a = "asdf" } ) );
Console.WriteLine( $"b:{b.b}" );
}
catch( JsonException ex )
{
Console.WriteLine( $"Json error: {ex.Message}" );
}
}
}
public class A
{
public A() {}
public string a { get; set; }
}
public class B
{
public B() {}
public string b { get; set; }
public C c { get; set; }
}
public class C
{
public C() {}
public int c { get; set; }
}
}
My expectation would be to throw a JsonException
as described in Microsoft documentation. What I get instead in the Console.WriteLine( $"b:{b.b}" )
is an object of B
with every property containing null
.
Am I missing something?
MissingMemberHandling
orItemRequired
functionalities in system.text.json, then it doesn't exist. – dbc