Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonSerializer.Deserialize expected to throw exception when deserializing different class

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?

like image 264
SzeliTom Avatar asked Mar 15 '26 20:03

SzeliTom


1 Answers

Based on documentation, the excpetion was thrown if :

The JSON is invalid.
-or-
TValue is not compatible with the JSON.
-or-
A value could not be read from the reader.

The code :

JsonSerializer.Serialize( new A { a = "asdf" } )

Geneate json like :

{ "a", "asdf" }

So no exception was thrown because :
1 - The Json is valid.
2 - B is compatible with this Json, it's like {}, b and c are not exist in the json, so will be null after deserialization.
3 - The reader can read the Json.

The exception will be raised if the json for example is like : "" or []

I hope you find this helpful.

like image 147
Mohammed Sajid Avatar answered Mar 18 '26 08:03

Mohammed Sajid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!