2017-09-05 33 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