我有以下的类:
public class TriGrid
{
private List<HexTile> _hexes;
//other private fields...
//other public proprerties
}
我的目标是只序列化_hexes
字段,所以我创建了以下ContractResolver:
internal class TriGridContractResolver : DefaultContractResolver
{
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
return new List<MemberInfo> { objectType.GetMember("_hexes", BindingFlags.NonPublic | BindingFlags.Instance)[0] };
}
}
而当我想要序列化TriGrid的实例时,我会这样做:
var settings = new JsonSerializerSettings()
{
ContractResolver = new TriGridContractResolver()
};
var json = JsonConvert.SerializeObject(someTriGrid, settings);
string strintJson = json.ToString();
但是当我检查 strintJson
的值时,它总是 "{}"
。 _hexes
有元素,不是空的。如果我序列化一个特定的 HexTile
,它会按预期工作。我在这里做错了什么吗?