Using DataContractJsonSerializer to create a Non X

2019-08-13 03:46发布

问题:

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