Newtonsoft. Json ignores attributes dynamically when Json is output, while newtonsoft. json ignores attributes.
I. Preface
Recently, the project used Json to interact with other clients, with the help of Newtonsoft. Json.
The output Json content varies depending on different business scenarios. You can use Newtonsoft to ignore attributes. for Json features, you can add the feature [JsonIgnore] before the object, but sometimes different attributes of the same object are output in different places according to the business requirements, therefore, the method for adding features obviously cannot meet the requirements. For example, A user table requires A password in scenario A, and B does not.
Ii. Solution
You can override the DefaultContractResolver class of Newtonsoft. Json.
Step 1: Inherit defaconcontractresolver
The new class inherits Newtonsoft. Json class DefaultContractResolver and overwrites the CreateProperties method. The Code is as follows:
Public class Identifier: DefaultContractResolver {IEnumerable <string> lstInclude; public identifier (IEnumerable <string> includeProperties) {lstInclude = includeProperties;} protected override IList <JsonProperty> CreateProperties (Type type Type, memberSerialization memberSerialization) {return base. createProperties (type, memberSerialization ). toList (). findAll (p => lstInclude. contains (p. propertyName); // attributes to be output }}}}
Step 2: Usage
Assume that the object list to be converted to Json is Product. Scenario 1: The Price attribute in this list does not need to be converted to Json to the front-end. Scenario 2, the ShopID and Count attributes in this list do not need to be converted to Json to the front-end. The Code is as follows:
List <Product> ProductList = new List <Product> {new Product {ShopID = 1, Price = 10, Count = 4, Name = "item 1 "}, new Product {ShopID = 2, Price = 11, Count = 3, Name = "item 2"}, new Product {ShopID = 1, Price = 12, Count = 1, name = "item 3"}, new Product {ShopID = 2, Price = 17, Count = 10, Name = "item 4"}, new Product {ShopID = 3, price = 13, Count = 2, Name = "Item 5" }}; // scenario 1 string jsonString = JsonConvert. serializeObject (ProductList, Formatting. indented, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling. ignore, ContractResolver = new JsonPropertyContractResolver (new List <string> {"ShopID", "Name", "Count"}); Console. writeLine ("scenario 1:" + jsonString); // scenario 2 JsonSerializerSettings settings = new JsonSerializerSettings (); settings. formatting = Formatting. indented; settings. referenceLoopHandling = ReferenceLoopHandling. ignore; settings. contractResolver = new JsonPropertyContractResolver (new List <string> {"Name", "Price"}); Console. writeLine ("Scenario 2:" + JsonConvert. serializeObject (ProductList, settings ));
Output result: