Json.net Async when writing to File

Boas Enkler picture Boas Enkler · Mar 26, 2013 · Viewed 8.2k times · Source

Json.net has the async functions for converting an object to json like:

json = await JsonConvert.DeserializeObjectAsync<T>

But when I want to write an object to a json file it seems better to me to do it directly using a file Stream.

So i think it should be something like this:

 var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);

    using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
    {
        using (StreamWriter sw = new StreamWriter(fileStream.AsStreamForWrite()))
        {
            using (JsonWriter jw = new JsonTextWriter(sw))
            {
                jw.Formatting = Formatting.Indented;

                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(jw, obj);
            }
        }

But on the JsonSerzializer Object I can't find async methods. Also I think that IO operations shouldn't be placed in a own thread.

What is the recommended approach ?

Answer

svick picture svick · Mar 26, 2013

Json.NET doesn't really support asynchronous de-/serialization. The async methods on JsonConvert are just wrappers over the synchronous methods that run them on another thread (which is exactly what a library shouldn't do).

I think the best approach here would be to run the file access code on another thread. This won't give you the full advantages of async (it will waste a thread), but it won't block the UI thread.