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?
All fields, both public and private, are serialized and properties are ignored. This can be specified by setting MemberSerialization. Fields on a type with the JsonObjectAttribute or by using the . NET SerializableAttribute and setting IgnoreSerializableAttribute on DefaultContractResolver to false.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.
Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.
Serialization is the process of encoding the from naive data type to JSON format. The Python module json converts a Python dictionary object into JSON object, and list and tuple are converted into JSON array, and int and float converted as JSON number, None converted as JSON null.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With