Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonSerializer.Deserialize can't inferred the usage

if I pass a string just to the method, the VS2019 give error that the usage can't be inferred.

if I write like this

JsonSerializer.Deserialize(text);
JsonSerializer.Deserialize(text.AsSpan());

both are giving the same error. as a string is convertible to the span.

but as mentioned in the Deserialize Documentation, the none generic type should work. but what I'm getting in here is the generic type.

Json Fiddle

I tried to google but didn't lead to any result.

enter image description here

like image 251
Mohammad Hossein Amri Avatar asked Mar 15 '26 15:03

Mohammad Hossein Amri


1 Answers

The methods that you highlighted take one type parameter, which is the type of C# object that holds deserialized data. You need to either specify the type parameter, or use an overload that takes type of the object as the second parameter:

using System;
using System.Text.Json;

namespace ConsoleApp1
{
    class Data
    {
        public bool Enabled { get; set; }

        public override string ToString()
        {
            return Enabled.ToString();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            String json = "{ \"Enabled\" : true }";
            // Using 2 different overload to deserialize data.
            Data data = JsonSerializer.Deserialize<Data>(json);
            Console.WriteLine(data);
            var data2 = JsonSerializer.Deserialize(json, typeof(Data));
            Console.WriteLine(data2);
        }
    }
}
like image 134
LeffeBrune Avatar answered Mar 17 '26 06:03

LeffeBrune