Bsa0 Bsa0 - 1 year ago 123
C# Question 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
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
is always
. The
has elements, it is not empty. If I serialize one particular
it works as expected. What I am doing wrong here?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download