![](/img/trans.png)
[英]Custom Json.NET contract resolver for lowercase underscore to CamelCase
[英]Overriding a property value in custom JSON.net contract resolver
我正在嘗試實現一個自定義的JSON.net IContractResolver,它將用指定的字符串替換所有null屬性值。 我知道這個功能可以通過序列化類型成員的屬性獲得; 這是我們正在考慮的替代路線。
到目前為止我的解析器實現如下。 StringValueProvider是一個IValueProvider的簡單實現,它不會影響問題,這是我無法弄清楚如何獲取property
的值,因為我不知道提供member
的實例的這個方法所以我不能將它作為參數傳遞給GetValue()
(在代碼示例中標記為WHAT-GOES-HERE?)。
有沒有辦法可以從member
或property
獲得我需要的東西?
public class NullSubstitutionPropertyValueResolver : DefaultContractResolver
{
private readonly string _substitutionValue;
public NullSubstitutionPropertyValueResolver(string substitutionValue)
{
_substitutionValue = substitutionValue;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty result = base.CreateProperty(member, memberSerialization);
PropertyInfo property = member as PropertyInfo;
if (property == null)
{
return result;
}
// What do I use here to get the property value?
bool isNull = property.GetValue(WHAT-GOES-HERE?) == null;
if (isNull)
{
result.ValueProvider = new StringValueProvider(_substitutionValue);
}
return result;
}
}
合同解析器與實例無關,它與類型有關。 價值提供者關注實例。 在合同解析程序中,您根據屬性類型決定是否應將值提供程序應用於屬性(例如,您可能只想在string
屬性上使用StringValueProvider
?)然后,使值提供程序存儲引用屬性(在構造函數中傳遞它以及替換值)。 在值提供程序中,您可以從對象實例中讀取值,檢查它是否為null並執行適當的值替換。
代碼看起來應該是這樣的:
public class NullSubstitutionPropertyValueResolver : DefaultContractResolver
{
private readonly string _substitutionValue;
public NullSubstitutionPropertyValueResolver(string substitutionValue)
{
_substitutionValue = substitutionValue;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty result = base.CreateProperty(member, memberSerialization);
PropertyInfo property = member as PropertyInfo;
if (property.PropertyType == typeof(string))
{
result.ValueProvider = new StringValueProvider(property, _substitutionValue);
}
return result;
}
}
public class StringValueProvider : IValueProvider
{
private PropertyInfo _targetProperty;
private string _substitutionValue;
public StringValueProvider(PropertyInfo targetProperty, string substitutionValue)
{
_targetProperty = targetProperty;
_substitutionValue = substitutionValue;
}
// SetValue gets called by Json.Net during deserialization.
// The value parameter has the original value read from the JSON;
// target is the object on which to set the value.
public void SetValue(object target, object value)
{
_targetProperty.SetValue(target, value);
}
// GetValue is called by Json.Net during serialization.
// The target parameter has the object from which to read the value;
// the return value is what gets written to the JSON
public object GetValue(object target)
{
object value = _targetProperty.GetValue(target);
return value == null ? _substitutionValue : value;
}
}
這是一個有效的演示: https : //dotnetfiddle.net/PAZULK
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.