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?
Asked
Active
Viewed 3,029 times
4
-
duplicate: https://stackoverflow.com/questions/26873755/json-serializer-object-with-internal-properties – CAD bloke Feb 19 '18 at 13:24
1 Answers
5
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.

Aaron Hudon
- 5,280
- 4
- 53
- 60

Jonathon Chase
- 9,396
- 21
- 39
-
Interesting - this seems to have done the trick - I've been messing about with `InternalsVisibleTo`! Is there a way I don't have to do this for each property that has an internal getter/setter as there are quite a few? – user3791372 Jan 02 '16 at 05:15
-
2You can decorate the class with `[JsonObject(MemberSerialization.Fields)]`. You can also use a custom contract resolver, as shown here: http://stackoverflow.com/a/24107081/5402620 – Jonathon Chase Jan 02 '16 at 05:24