2
votes

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?

1
If you are looking for the equivalent of Newtonsoft's MissingMemberHandling or ItemRequired functionalities in system.text.json, then it doesn't exist.dbc
From the docs: Required properties... System.Text.Json doesn't throw an exception if no value is received for one of the properties of the target type... To make deserialization fail if no property is in the JSON, implement a custom converter.dbc
And also from the docs MissingMemberHandling... System.Text.Json ignores extra properties in the JSON, except when you use the [JsonExtensionData] attribute. There's no workaround for the missing member feature.dbc
Ok I got it. Thanks for the helpSzeliTom

1 Answers

1
votes

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.