首页 > 解决方案 > 如何将私有字段添加到json

问题描述

我有一个带有私有字段的类,我希望它们在 JSON 字符串中,稍后我将写入文本文件。

like so

class User
{
        private string userEmail;
        private string userPassword;
        public bool isconnected;
}

class WriteToFile
{
   public Dictionary<string,User> write(){
           if (File.Exists(path))
           {
                    File.WriteAllText(path, string.Empty);
                    string json = JsonConvert.SerializeObject(dictionary);
                    File.WriteAllText(path, json);
           }
   }
}

我希望在 json 变量中包含他的值是带有他的 PRIVATE 字段的用户对象的字典。(另外,如果您可以编写一个将在 WriteToFile 类中的函数,而不是在其他类中)

谢谢!

标签: c#jsondictionaryprivate

解决方案


声明您的私有财产JsonProperty

public class User
{
    [JsonProperty]
    private string userEmail = "@abc";
    [JsonProperty]
    private string userPassword = "def";
    public bool isconnected = true;
}

推荐阅读