簡體   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