Bsa0 Bsa0 - 1 month ago 14
C# Question

Json.net serialize specific private field

I have the following class:

public class TriGrid
{
private List<HexTile> _hexes;
//other private fields...
//other public proprerties
}


My goal is to serialize only the
_hexes
field, so I created the following ContractResolver:

internal class TriGridContractResolver : DefaultContractResolver
{
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
return new List<MemberInfo> { objectType.GetMember("_hexes", BindingFlags.NonPublic | BindingFlags.Instance)[0] };
}
}


and when I want to serialize an instance of TriGrid I do:

var settings = new JsonSerializerSettings()
{
ContractResolver = new TriGridContractResolver()
};
var json = JsonConvert.SerializeObject(someTriGrid, settings);
string strintJson = json.ToString();


but when I check the value of
strintJson
is always
"{}"
. The
_hexes
has elements, it is not empty. If I serialize one particular
HexTile
it works as expected. What I am doing wrong here?

Answer

There is no need to implement a custom DefaultContractResolver. The solution is to put [JsonProperty] on _hexes and [JsonIgnore] on all the other properties and fields.