Search code examples
c#jsonserializationderived-classsystem.text.json

Problems with C# json serialization


I am doing a program with some derived classes for a game. I have to use json serialization to save the progress of the player but when i serialize the Player class it only serialize the types of his mother class Character. I rewrited the code with just the player but i also have this problem with all my classes in the game that are derived from something

using System.Text.Json.Serialization;using System.Globalization;
using System.Reflection;
using System.Configuration;
using System.Timers;
using System.Text.Json;
using System.ComponentModel;namespace Fix_Salvataggio;


[JsonDerivedType(typeof(Player), typeDiscriminator:"Player")]
public class Character
{
    public string? Name {get; set;}
    public int HP {get; set;}
    public Character() {}
    public Character(string? Name, int HP) 
    {
        this.Name = Name;
        this.HP = HP;
    }
}

public class Player : Character
{
    public int Sanity;
    public int ActualWeight;
    private int Maxweight;
    public Player() {}
    public Player(string? Name, int HP, int Sanity, int Maxweight) : base(Name, HP)
    {        
        this.Sanity = Sanity;
        this.ActualWeight = 0;
        this.Maxweight = Maxweight;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Player player = new Player("Mario", 100, 100, 100);


        var options = new JsonSerializerOptions { WriteIndented = true };

        string fileName = "SavePlayer.json";
        string jsonString = JsonSerializer.Serialize(player, options);// + JsonSerializer.Serialize(rooms) + JsonSerializer.Serialize(done1) + JsonSerializer.Serialize(done2) + JsonSerializer.Serialize(done3);
        File.WriteAllText(fileName, jsonString);
    }
}

I also asked my university professer but he was not able to find the error, he made me add in the code this line [JsonDerivedType(typeof(Player), typeDiscriminator:"Player")] because he said that in json serialization in c# u have to add this to serialize derivated classes sometimes, but it still dosen't work

I tried to add empty constructor, to link constructor of the two classes but it still dosent work


Solution

  • JsonDerivedType is not needed.

    Either make Sanity and ActualWeight properties:

    public int Sanity { get; set; }
    public int ActualWeight { get; set; }
    

    or ask JsonSerializer to serialize fields too:

    var options = new JsonSerializerOptions { WriteIndented = true, IncludeFields = true };