Home Ask Login Register

Developers Planet

Your answer is one click away!

user1058410 February 2016

Error when using json.net JsonConverter to serialize/derserialize a dataset

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");

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?


Ageonix February 2016

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

Post Status

Asked in February 2016
Viewed 2,718 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life