Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like the opposite of a JsonIgnore?

Tags:

c#

json.net

The JsonIgnore attribute can be used to ignore certain properties in serialization. I was wondering if it is possible to do the opposite of that? So a JsonSerializer would ignore every property EXCEPT when there is a special attribute on it?

like image 794
user2657943 Avatar asked Dec 23 '22 18:12

user2657943


1 Answers

Yes there is. When you mark your class with [JsonObjectAttribute] and pass the MemberSerialization.OptIn parameter, member serialization is opt-in. Then mark your members with [JsonProperty] to include them for serialization.

[JsonObject(MemberSerialization.OptIn)]
public class Person
{
    [JsonProperty]
    public string Name { get; set; }

    // not serialized because mode is opt-in
    public string Department { get; set; }
}
like image 188
Myrtle Avatar answered Feb 03 '23 16:02

Myrtle