Question

I tried to serialize and deserialize a ConcurrentBag using JSON.NET:

 var bag = new ConcurrentBag<int>(){2};
 var jsonSerializer = new JsonSerializer();
 using(var aStream = new MemoryStream())
 { 
    var sw = new BsonWriter(aStream); 
    jsonSerializer.Serialize(sw, bag);

    aStream.Position = 0;   

    var rw = new BsonReader(aStream);        
    jsonSerializer.Deserialize(rw,bag.GetType()); 
 }

and I got this exception:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Concurrent.ConcurrentBag`1[System.Int32]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path '0'.

If I don't pass the type as the second argument to the deserializer it's fine but I have a generic object as output.

Does anybody have an idea why this happens?

Was it helpful?

Solution

My guess would be that you want to convert that bag into an array before serializing. JSON.NET probably isn't fully featured enough to have routines for all of the System.Concurrent collection types (and it probably shouldn't be- those types are implementation details). In your case, you might want to try something like this:

// Add a "using System.Linq" somewhere above...
var bag = new ConcurrentBag<int>(){2};
var jsonSerializer = new JsonSerializer();
using(var aStream = new MemoryStream())
{ 
   var sw = new BsonWriter(aStream); 
   jsonSerializer.Serialize(sw, bag.ToArray());

   aStream.Position = 0;   

   var rw = new BsonReader(aStream);        
   var intArray = jsonSerializer.Deserialize(rw, typeof(int[])); 
   var deserializedBag = new ConcurrentBag<int>(intArray); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top