Search code examples
c#jsondictionaryprivate

How to add private fields to json


I have a class with private fields and I want them in the JSON string that later I will write into a text file.

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

I would like that in the json variable will contain the dictionary that his value is the User object WITH his PRIVATE fields. (Also if you can write a function that will be in the WriteToFile class, not in other class)

Thanks!


Solution

  • Declare your private properties with JsonProperty

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