1

I'm using Jsonconverter to serialize and deserialize a dataset. Everything works fine, except in the case where one of the tables has a nullable uniqueidentifier column. So if I make my dataset like

var set = new DataSet();
var adapter = newSqlDataAdapter();
adapter.SelectCommand = new SqlCommand("Select * from mytable");
adapter.Fill(set);

where mytable has a nullable uniqueidentifer column and the first several values are null, and then serialize

MemoryStream ms = new MemoryStream();
using (BsonWriter bw = new BsonWriter(ms))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(bw, set);
}
string bson = Convert.ToBase64String(ms.ToArray());

where bson is the string representation of the dataset, everything seems to work great. But when I try to deserialze the set

byte[] data = Convert.FromBase64String(bson);
MemoryStream ms2 = new MemoryStream(data);
using (BsonReader reader = new BsonReader(ms2))
{
    reader.ReadRootValueAsArray = false;
    JsonSerializer serializer = new JsonSerializer();
    DataSet set2 = serializer.Deserialize<DataSet>(reader);
}

It throws an exception the first time it tries to write the a value where the other values are null. The exceptions message is Error converting value a6934b26-3757-469a-9735-41558e4c0985 to type 'System.String'. Path 'Table[13].MyNullableGuidColumn'.

As a work around I've looped through the table changing the nulls to guid.empty, but that doesn't seem like the best answer.

So does anybody know of a way to make deserialization work and keep the nulls as null?

user1058410
  • 135
  • 1
  • 9
  • Possibly related: http://stackoverflow.com/questions/32726718/deserialize-a-datatable-with-a-missing-first-column – dbc Feb 08 '16 at 22:41

1 Answers1

1

Try using this technique instead when serializing your data:

string correctData = JsonConvert.SerializeObject(set, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

Some more information if you need it: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

Ageonix
  • 1,748
  • 2
  • 19
  • 32