When serializing a JSON I get trailing null characters which makes my unit test fail. The serializer looks like this:
public static string SerializeJSON<T>(T ObjectToSerialize)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(ObjectToSerialize.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream, Encoding.UTF8, false, true))
{
serializer.WriteObject(jsonWriter, ObjectToSerialize);
}
return Encoding.UTF8.GetString(memoryStream.GetBuffer());
}
}
I have written a unit test for it that looks like this:
[TestMethod]
public void SerializeJSON()
{
string testJSON = File.ReadAllText(@"Util\\TestCurrency.json");
Currency currency = StaticExamples.ccy1;
string json = SerializeUtil.SerializeJSON(currency);
Assert.AreEqual(testJSON, json);
}
Which compares the serialized currency to the file example, they should be identical. But the test fails saying:
Message: Assert.AreEqual failed. Expected:<{
"code": "USD",
"currencyId": 1,
"name": "Dollar",
"status": "Active"
}>.
Actual:<{
"code": "USD",
"currencyId": 1,
"name": "Dollar",
"status": "Active"
}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0>.
The trailing characters are null characters from what I understand. Any idea of why they appear? It works to Deserialize this JSON again but my test still fails. This is tha class being serialized:
public class Currency
{
public int currencyId { get; set; }
public string code { get; set; }
public string name { get; set; }
public string status { get; set; }
}
EDIT with answer Thanks to @DavidG I changed the way I converted the stream to a string and it works know. This is the generic serializer code for anyone who wants it:
public static string SerializeJSON<T>(T ObjectToSerialize)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(ObjectToSerialize.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream, Encoding.UTF8, false, true))
{
serializer.WriteObject(jsonWriter, ObjectToSerialize);
}
memoryStream.Position = 0;
return new StreamReader(memoryStream).ReadToEnd();
}
}