我有以下课程:
public class TriGrid { private List<HexTile> _hexes; //other private fields... //other public proprerties }
我的目标是仅序列化_hexes字段,因此我创建了以下ContractResolver:
_hexes
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它将按预期工作。我在这里做错了什么?
strintJson
"{}"
HexTile
无需实现自定义DefaultContractResolver。解决的办法是把[JsonProperty]上_hexes和[JsonIgnore]所有其他属性和领域。
DefaultContractResolver
[JsonProperty]
[JsonIgnore]