C# json 序列化问题

问题描述 投票:0回答:1

我正在编写一个带有一些游戏派生类的程序。我必须使用 json 序列化来保存播放器的进度,但是当我序列化 Player 类时,它只序列化他的母类 Character 的类型。我只用播放器重写了代码,但我也遇到了游戏中所有源自某些东西的类的问题

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);
    }
}

我也问了我的大学教授,但他找不到错误,他让我在代码中添加这一行

[JsonDerivedType(typeof(Player), typeDiscriminator:"Player")]
因为他说在c#中的json序列化中有时必须添加这个来序列化派生类,但它仍然不起作用

我尝试添加空构造函数,以链接两个类的构造函数,但它仍然不起作用

c# json class serialization derived-class
1个回答
0
投票

JsonDerivedType
不需要。

创建 Sanity 和 ActualWeight 属性:

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

或者要求 JsonSerializer 序列化字段:

var options = new JsonSerializerOptions { WriteIndented = true, IncludeFields = true };
© www.soinside.com 2019 - 2024. All rights reserved.