繁体   English   中英

将 object 转换为 JSON 格式会导致“{}”

[英]Converting object to JSON format results in “{}”

[Serializable]
class temp
{
    int id;
    int age;

    public temp(int id,int age)
    {
        this.id = id;
        this.age = age;
    }
}

    temp ob = new temp(4, 4);  
        string json = JsonUtility.ToJson(ob);
        System.IO.File.WriteAllText(Application.streamingAssetsPath + "/User.json", json)

嘿伙计们,我正在尝试将我的 object 转换为 JSON 并且我得到“{}”任何帮助?

如果您阅读 Unity,s Script Serialization ,您会发现序列化值的规则:

Unity 中的序列化程序在实时游戏环境中运行。 这对性能有很大影响。 因此,Unity 中的序列化与其他编程环境中的序列化行为不同。 以下部分概述了如何在 Unity 中使用序列化。 要使用字段序列化,您必须确保它:

  • public ,或具有[SerializeField]属性
  • 不是static
  • 不是const
  • 不是readonly
  • 具有可以序列化的字段类型。

请注意,默认情况下c#如果您没有明确告诉它,否则标准访问 scope 是private的 => 未序列化!


你的 class 应该看起来像

[Serializable]
class temp
{
    public int id;
    public int age;

    public temp(int id,int age)
    {
        this.id = id;
        this.age = age;
    }
}

或者,如果出于某种原因您想避免public这些值,那么

[Serializable]
class temp
{
    [SerializeField] private int id;
    [SerializeField] private int age;

    public temp(int id,int age)
    {
        this.id = id;
        this.age = age;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM