Using DataContractJsonSerializer to create a Non XML Json file

余生长醉 提交于 2019-12-11 08:27:27

问题


I want to use the DataContractJsonSerializer to serialize to file in JsonFormat. The problem is that the WriteObjectmethod only has 3 options XmlWriter, XmlDictionaryWriter and Stream.

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?


回答1:


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...




回答2:


I am actually quite terrified to claim to know something that Jon Skeet doesn't, but I have used code similar to the following which produces the Json text file and maintains proper indentation:

var js = new DataContractJsonSerializer(typeof(T), _knownTypes);
using (var stream = File.Create(path))
{
    using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, true, true, "\t"))
    {
        js.WriteObject(writer, item);
        writer.Flush();
    }
}

(as suggested here.)



来源:https://stackoverflow.com/questions/31130829/using-datacontractjsonserializer-to-create-a-non-xml-json-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!