2017-09-05 32 views
0

我在C#中创建一个XmlDoc并使用Newtonsoft序列化为JSON。它的工作原理,但我得到了一堆在JSON结尾处显示为“NUL”的东西。不知道为什么。任何人见过这个?newtonsoft SerializeXmlNode trailing nulls

CODE:

XmlDocument xmlDoc = BuildTranslationXML(allTrans, applicationName, language); 

// Convert the xml doc to json 
// the conversion inserts \" instead of using a single quote, so we need to replace it 
string charToReplace = "\""; 
string jsonText = JsonConvert.SerializeXmlNode(xmlDoc); 

// json to a stream 
MemoryStream memoryStream = new MemoryStream(); 
TextWriter tw = new StreamWriter(memoryStream); 
tw.Write(jsonText); 
tw.Flush(); 
tw.Close(); 

// output the stream as a file 
string fileName = string.Format("{0}_{1}.json", applicationName, language); 
return File(memoryStream.GetBuffer(), "text/json", fileName); 

文件送达需要调用网页,浏览器会提示用户保存文件。打开文件时,它显示正确的JSON,但也包含所有的尾随空值。见下面(希望的计算器链接作品)图像:

file screenshot

回答

2

GetBuffer()方法返回MemoryStream的内部表示。使用ToArray()取而代之的是获取内部数组中有Newtonsoft已放入数据的部分。

+0

太棒了!非常感谢,它的工作。 –

+0

@ToddWilloughby - 在这种情况下,您可能会[接受此答案](https://meta.stackexchange.com/q/5234)。 – dbc