我有以下设置:
public abstract class A
{
[JsonIgnore]
public abstract Type Foo { get; }
}
public abstract class B : A
{
public override Type Foo { get { return typeof(D); } }
}
public class C : B
{
}
public abstract class D
{
}
我的问题是当我通过以下方式序列化C的实例时:
JsonConvert.SerializeObject(instanceOfC, serializationSettings));
生成的JSON包含属性Foo的条目。这是预期的结果吗?
我的serializationSettings
如下:
JsonSerializerSettings _serializationSettings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
TypeNameHandling = TypeNameHandling.All,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
编辑:使用Json.NET 6.0.0和.NET 4.5。
答案 0 :(得分:0)
我遇到了同样的问题,我通过指定" ContractResolver"解决了这个问题。像这样的JsonSerializerSettings的属性(为你初始化所有必需的属性):
var settings = new JsonSerializerSettings
{
Formatting = Formatting.None,
ContractResolver = new PublicNotInternalPropertiesCamelCaseContractResolver()
};
这是我的PublicNotInternalPropertiesCamelCaseContractResolver:
public class PublicNotInternalPropertiesCamelCaseContractResolver : CamelCasePropertyNamesContractResolver
{
#region Overrides of DefaultContractResolver
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
var members = base
.GetSerializableMembers(objectType)
.Where(m => m.GetCustomAttribute<InternalAttribute>() == null)
.ToList();
return members;
}
#endregion
}
我必须创建一个属性&#34; InternalAttribute&#34;,因为这个解决方案由于某些原因不适用于JsonIgnoreAttribute:
public class InternalAttribute : Attribute
{
}
我这样使用它:
public abstract class RavenDbEntity
{
private string _dbKey;
[Internal]
public string DbKey
{
get { return _dbKey; }
set
{
_dbKey = value;
Id = int.Parse(value.Split('/')[1]);
}
}
public int Id { get; set; }
}
因此输出JSON将没有DbKey属性