基类没有被反序列化

时间:2012-09-17 11:49:10

标签: c# json

我正在为此项目使用Newtonsoft.Json .Net for 4.0

家长班:

public class CLiveThing
{
    private object lawk = new object();

    public Action<double> hp_cur_changed;
    public Action<double> hp_max_changed;

    public double hp_max { get; private set; }
    public double hp_cur { get; private set; }

    public void change_hp_max(double val)
    {
        lock (lawk)
        {
            hp_max += val;
            if (hp_max_changed != null)
                hp_max_changed(hp_max);
        }
    }

    public void change_hp_cur(double val)
    {
        lock (lawk)
        {
            hp_cur += val;
            if (hp_cur_changed != null)
                hp_cur_changed(hp_cur);
        }
    }
}

儿童班:

public class CPlayer : CLiveThing
{
    public int id { get; private set; }

    public CPlayer(int id)
    {
        this.id = id;
    }

    /*
     * Network
    */

    public string Serialize()
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(this);
    }
    public static CPlayer Deserialize(string val)
    {
        return Newtonsoft.Json.JsonConvert.DeserializeObject<CPlayer>(val);
    }
}

服务器(使用Players.CPlayers管理具有通用集合的所有玩家)

Players.CPlayers.Serialize()

Players.CPlayers.Serialize序列化服务器内存中的所有玩家,每行一个

像这样:

public static string Serialize()
{
    players_lock.AcquireReaderLock(Timeout.Infinite);
    string str = "";
    foreach (CPlayer player in players.Values)
    {
        str += player.Serialize();
        str += Environment.NewLine;
    }

    players_lock.ReleaseReaderLock();
    return str;
}

客户端

我在Players.CPlayers.Deserialize循环中放了一个断行,它反转了服务器所做的事情。

foreach (string line in split)
{
    if (line.Length > 0)
    {
        CPlayer player = CPlayer.Deserialize(line);
        addOrReplace(player.id, player);
    }
}

以下是一行示例:

进展情况:

"{\"hp_cur_changed\":null,\"hp_max_changed\":null,\"id\":1,\"hp_max\":100.0,\"hp_cur\":100.0}"

CPlayer.Deserialize():

out

它仅反序列化ID并忽略父类中的属性。这很奇怪,因为服务器端确实正确地序列化了它。有谁能告诉我如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我无法找到官方参考,为什么它的工作方式如此,但至少有两种方法可以解决您的问题:

将您的基类属性setter声明为public

 public double hp_cur { get; set; }

 public double hp_max { get; set; }

或使用JsonProperty属性注释它们:

 [JsonProperty]
 public double hp_max { get; private set; }

 [JsonProperty]
 public double hp_cur { get; private set; }
相关问题