Json.NET async support with custom JsonConverter
Asked Answered
C

1

12

Json.NET version 10 added support to async serialization. Version 11 added support to generic JsonConverter<T>.

The problem is that JsonConverter<T> and previous JsonConverter only support synchronous methods.

i.e.: public override void WriteJson(...)

The JsonWriter passed to WriterJson supports both synchronous and asynchronous methods like:

writer.WritePropertyNameAsync() and writer.WritePropertyName()

But since WriteJson itself is synchronous, the async option is not usable here.

Is it possible to have a custom JsonConverter with async methods?

Chequer answered 2/4, 2018 at 11:21 Comment(13)
Why don't u just use Task.Run(new Action(WriteJson));Wagshul
I'd be blocking a thread pool thread that way. The serialized object will written async due to I/OChequer
Why don't you create a feature request issue in the GitHub repo?Fassett
I want to make sure I'm not missing anything. There might be a different approach to this that I'm unaware.Chequer
I think it's not yet supported. There is related (but not the same) open issue about JsonConvert.SerializeAsync here: github.com/JamesNK/Newtonsoft.Json/issues/1193Mohn
@BrunoGarcia but the thread is not gonna be blocked if u await the Task. is that wrong? so what is the purpose of creating new Task then?Wagshul
@ArgeKumandan I want to avoid using threads that are not needed instead of scheduling even more.Chequer
@Mohn thanks for that thread! I subscribed to it and I believe the result of that will be the answer to this thread.Chequer
Note that it's over the year old, so don't put much hopes into that being available soon :) Note that you can parse to JToken first (async) and then serialize to specific type with JToken.ToObject (no async needed at this point anyway).Mohn
I'm trying to serialize an object though. Writing to the stream directly to avoid allocating the whole thing in memory at any one point. That part is covered, missing only async with custom JsonConverter.Chequer
Yes I missed you are serializing. I thought to suggest JToken.FromObject, but since you don't want to hold whole object in memory also - I see no way with current api indeed.Mohn
Not sure why you want your JsonConverter to read/write asynchronously? At that time you are already provided with a writer and reader injected by the invoking serializer and I can't think of actual IO that could block your thread?Cheetah
Related though not duplicate: Deserializing to AsyncEnumerable using Newtonsoft.Json.Merganser
S
0

i don't think there is a way. but you can use JsonSerializer or JsonTextWriter

Schlimazel answered 2/9 at 20:1 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Toronto

© 2022 - 2024 — McMap. All rights reserved.