How to skip standard JavaScript array serialization for IEnumerable types in Json.Net?

Some custom types that implement IEnumerable do not necessarily support collections. They can be generated dynamically, for example, using yield or LINQ. Here is an example:

public class SOJsonExample { public class MyCustomEnumerable : IEnumerable<KeyValuePair<int,float>> { public List<int> Keys { get; set; } public List<float> Values { get; set; } public MyCustomEnumerable() { Keys = new List<int> { 1, 2, 3 }; Values = new List<float> { 0.1f, 0.2f, 0.3f }; } public IEnumerator<KeyValuePair<int, float>> GetEnumerator() { var kvps = from key in Keys from value in Values select new KeyValuePair<int, float>(key, value); return kvps.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } 

I found that the default serialization of Json.NET is to enumerate each value and store the values ​​in a JavaScript array (which I don't want). Then, by default, the deserializer will not be able to deserialize the collection because it cannot be populated. In these cases, I would instead want Json.NET to skip serializing the default JavaScript array and just keep the class members.

All I want is my keys and values ​​- is there any quick access method, or do I need to implement my own serializer?

Checked this and none of which is exactly my question. I scanned the documentation , but did not find what I was looking for (maybe I was looking for the wrong place).

(Edit # 1 - improved clarity)

(Edit # 2 - answered my question ... see below)

+7
source share
1 answer

Answered my own question - see excellent documentation on IEnumerable, Lists and Arrays :

.NET lists (types inheriting from IEnumerable) and .NET arrays are converted to JSON arrays. Because JSON arrays only support a range of values, not properties, any additional properties and fields declared in .NET collections are not serialized. In situations where a JSON array is not needed, a JsonObjectAttribute can be placed in a .NET type that implements IEnumerable to cause the type to be serialized as a JSON object.

So for my example:

 [JsonObject] public class MyCustomEnumerable : IEnumerable<KeyValuePair<int,float>> { ... } 
+12
source

All Articles