使用DataContractJsonSerializer创建Non XML Json文件 [英] Using DataContractJsonSerializer to create a Non XML Json file
问题描述
我想使用DataContractJsonSerializer序列化为JsonFormat中的文件。
问题是 WriteObject
方法仅具有3个选项XmlWriter,XmlDictionaryWriter和Stream。
I want to use the DataContractJsonSerializer to serialize to file in JsonFormat.
The problem is that the WriteObject
method only has 3 options XmlWriter, XmlDictionaryWriter and Stream.
To得到我想要的东西,我使用了以下代码:
To get what I want I used the following code:
var js = new DataContractJsonSerializer(typeof(T), _knownTypes);
using (var ms = new MemoryStream())
{
js.WriteObject(ms, item);
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
using (var writer = new StreamWriter(path, false))
{
string jsonData = sr.ReadToEnd();
writer.Write(jsonData);
}
}
}
这是唯一的方法还是我错过了什么吗?
Is this the only way or have I missed something?
推荐答案
假设您只是想将文本写到文件中,不清楚为什么首先将其写入 MemoryStream
。您可以使用:
Assuming you're just trying to write the text to a file, it's not clear why you're writing it to a MemoryStream
first. You can just use:
var js = new DataContractJsonSerializer(typeof(T), _knownTypes);
using (var stream = File.Create(path))
{
js.WriteObject(stream, item);
}
这很简单,应该做您想要的...
That's rather simpler, and should do what you want...
这篇关于使用DataContractJsonSerializer创建Non XML Json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!