Click here to Skip to main content
15,917,709 members
Please Sign up or sign in to vote.
1.33/5 (2 votes)
See more:
i am using Newtonsoft json V 6.0.0 with C# i am serializing object using json.

My object contains various type of collection and i am serializing object after finish all search and getting response. Even i am getting exception

"System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)"

I am not able to track the object which is modifying during serialization. in my code serialization is running in thread in high frequency.

my code is
var Jsonsettings = new JsonSerializerSettings
               NullValueHandling = NullValueHandling.Ignore,
               DefaultValueHandling = DefaultValueHandling.Ignore,
               ContractResolver = new WBContractResolver()

var SerializedJson = JsonConvert.SerializeObject(this, Jsonsettings);

Thanks in advance !!!

Richard Deeming 7-May-15 8:41am    
"serialization is running in thread"

Are you trying to serialize a collection on one thread, whilst modifying it on another?

Unless you're using one of the concurrent collections[^] (or the immutable collections[^] available from NuGet), that won't work.

1 solution

The first line of the error message says that the collection was modified during serialization. Do you use a loop that removes items from this collection during serialization? Or is there another thread removing items from the collection?
Share this answer
Sudheer Kumar Tiwari 7-May-15 9:38am    
Hi bart;

i am not using any loop. I have use null handling and default handling in json setting may be it will be looping internally on object.
how we can handle this exception.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900