我有以下设置:
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。
我也遇到过同样的问题,我通过指定JsonSerializerSettings的"ContractResolver"属性来解决它,如下所示(为您初始化所有必要的属性):
var settings = new JsonSerializerSettings
{
Formatting = Formatting.None,
ContractResolver = new PublicNotInternalPropertiesCamelCaseContractResolver()
};
这是我的PublicNotInternalProperties CamelCaseContractResolver:
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
}
我不得不创建一个属性"InternalAttribute",因为这个解决方案由于某些原因无法使用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属性