Search code examples
c#json.netinternalclass-visibility

Allowing Newtonsoft's JsonConvert access to internal getter/setters


I have a class with internal getters/setters to prevent the user from accessing this functionality (I'm working with a REST api). However, this also means that JsonConvert doesn't have access to them. How can I allow JsonConvert access to the internal functionality?


Solution

  • You should be able to decorate them with the JsonPropertyAttribute.

    void Main()
    {
        var x = new Test();
        Console.WriteLine(JsonConvert.SerializeObject(x));
    }
    
    // Define other methods and classes here
    public class Test 
    {
        public Test()
        {
            TestProp = "test";
        }
    
        [JsonProperty]
        internal string TestProp { get; set; }
    }
    

    Output: {"TestProp":"test"}

    Using Linqpad.