Search code examples
c#dictionarytypestypeerrorsystem.text.json

Passing the right type to JsonSerializer in C#


I have a problem using JsonSerializer.Serialize to save a dictionary to file: it won't accept my object alone (implementation for two arguments is using a type as second argument, and when I try using the type of the dictionary, it says it doesn't fit the requirement).

I read these:
https://docs.microsoft.com/fr-fr/dotnet/api/system.text.json.jsonserializer.serialize?view=net-7.0;
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-6-0;
JsonConvert.SerializeObject vs JsonSerializer.Serialize
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/supported-collection-types?pivots=dotnet-7-0
But can't figure out what I'm doing wrong. Could you please explain me? Thanks

using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text.Json; //JsonSerializer;

namespace Modules;

public class Tracker : ModuleBase<SocketCommandContext>
{
    internal static Dictionary<int, SortedSet<string>>  playerTracker=
       new Dictionary<int,SortedSet<string>>{};

       [Command("w")]
       [Summary("write current tracker to file")]
       public async Task saveTracker ()
       {
           Console.WriteLine(JsonSerializer.Serialize(playerTracker));
           Console.WriteLine(playerTracker);
           using (StreamWriter file = File.CreateText(@"playerTracker.json"))
           {
        
           //JsonSerializer.Serialize(file,playerTracker, Dictionary<int, SortedSet<string>>);
           //CS0119
           JsonSerializer.Serialize(file,playerTracker);
           //CS1503 (arg 2) impossible to convert 'System.Collections.Generic.Dictionary<int,                      System.Collections.Generic.SortedSet<string>>' as 'System.Type' 
           }
       }
}

Solution

  • It looks like you're passing a StreamWriter where the overload you're trying to call takes a Stream. That's confusing the compiler, because it assumes you must be trying to use one of the overloads which takes the object to serialize as its first argument. It's therefore reporting a problem with your second argument, because it's not any of the things which would be allowed by any of those overloads.

    Try using File.Create instead of File.CreateText.

    using (FileStream file = File.Create(@"playerTracker.json"))