Say I have an object with this format:
new LookUpResponse
{
LookUpDetails =
new List<LookUpDetail>
{
new LookUpDetail
{
LookUpCode = "GB00B6RLLV55",
CitiCode = "GTUI",
UnitName = "Liontrust Asia Income A Inc",
UniverseCode = "O",
IsFundDriver = false
}
}
};
What I want is to allow users to select which child properties to return (e.g. selectField="LookUpDetail[LookUpCode,CitiCode]"
), then my code parses it, so I know for type LookupDetail,we want to return Lookkupcode and citicode.
Is it possible with newton.json?
I tried this:
public class SelectFieldsResolver : DefaultContractResolver
{
private readonly IEnumerable<string> _selectFields;
public SelectFieldsResolver(IEnumerable<string> selectFields)
{
_selectFields = selectFields;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = instance => {
if (!_selectFields.IsNullOrEmpty() && !_selectFields.Any(f => string.Equals(f, property.PropertyName, StringComparison.InvariantCultureIgnoreCase))) return false;
var value = instance?.GetType().GetProperty(property.PropertyName)?.GetValue(instance, null);
return value != null;
};
return property;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => {
var jp = CreateProperty(p, memberSerialization);
jp.ValueProvider = new NullToEmptyStringValueProvider(p);
return jp;
}).ToList();
}
}
However, the method CreateProperty and CreateProperties are only called on the root level (called on the LookUpDetails property), and what I want is that when the child object LookUpDetail is serialised, these functions should be called as well, so I can exclude the fields on children.
Is it Possible?