Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 949
Bsa0 Avatar asked Aug 14 '15 11:08

Bsa0


People also ask

Does JSON net serialize private fields?

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.

What is the difference between JSON and serialization?

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.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.

Does JSON serialize data?

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.


1 Answers

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.

like image 102
Bsa0 Avatar answered Oct 02 '22 12:10

Bsa0