简体   繁体   中英

json.net serializing only selected nested properties

I want to serialize objects using json.net and C#.Also I want only selected properties to be inside the final JSON object returned. I have two classes

public class EmployeeClass {
 
   [JsonProperty("className")]
   public string Name{ get; set;}
   
   [JsonProperty("hierUnitId")]
   public int? HierUnitId { get; set; }
   
   [JsonProperty("rvcOperatorOptions")]
   public List<OperatorOptions> RvcOperatorOptions{get; set;}
 
}

public class OperatorOptions{

     [JsonProperty("rvcObjNum")]
     public int? RvcObjectNum {get; set;}

     [JsonProperty("options")]
     public string Options {get; set;}

 }    

Now I have an EmployeeClass object which I want to serialize .

{   
   "className" : "EmpClass",
   "hierUnitId" : 101,
   "rvcOperatorOptions" : [
            { "rvcObjNum" : 10 , "options" : "00010011" } ,
            { "rvcObjNum" : 11 , "options" : "11110011" }
    ]

}

For that i have override the CreateProperties method of the DefaultContractResolver class for including only selected properties.Also i'm passing the list of properties to be included to the constructor of my CustomRetrieveResponseResolver class which is extending DefaultContractResolver .

private readonly IList<string> _propertiesToInclude;
public CustomRetrieveResponseResolver(IList<string> propertiesToInclude)
{
    _propertiesToInclude = propertiesToInclude;
}

I have a list of strings propertiesToInclude which have the name of properties to be included.

For ex:
propertiesToInclude = { "Name", "RvcOperatorOptions.RvcObjectNum" }

Now the problem is that in the list propertiesToInclude i have the relative names of the nested properties. I know that CreateProperties is going to be called twice one for EmployeeClass and then for OperatorOptions Class ( due to the List<OperatorOptions> RvcOperatorOptions inside EmployeeClass ). Is there any way of serializing in this manner? Like the output for the above object will be

{   
       "className" : "EmpClass",
       "rvcOperatorOptions" : [
                { "rvcObjNum" : 10 } ,
                { "rvcObjNum" : 11  }
        ]
    
}    

Can Someone help me in this ie serializing selected values with the using path of nested properties?

Use [JsonIgnore] attribute if you want to ignore properties when serializing/reserializing.

For dynamic exclusion on properties:

public class CustomPropertiesContractResolver : DefaultContractResolver
{
    private HashSet<string> _propertySet;
    
    public CustomPropertiesContractResolver(IEnumerable<string> propertyNames)
    {
        if (propertyNames != null)
        {
            _propertySet = new HashSet<string>(propertyNames, StringComparer.OrdinalIgnoreCase);
        }
    }
    
    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        List<MemberInfo> serializableMembers = null;
        var allMembers = base.GetSerializableMembers(objectType);
   
        if (_propertySet != null && _propertySet.Count > 0)
        {
            serializableMembers = allMembers.Where(m => !_propertySet.Contains(m.Name)).ToList();
        }
        return serializableMembers != null && serializableMembers.Count > 0 ? serializableMembers : allMembers;
    }
}

Usage

var serializedStr = JsonConvert.SerializeObject(employeeObj, new JsonSerializerSettings()
{
    ContractResolver = new CustomPropertiesContractResolver(new List<string>{"options"})
};);
     

To provide depth and be able to track contracts of nested properties, check this answer: Json.NET serialize by depth and attribute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM