0

I'm working on custom JsonConverter (where T is base type of objects supported by this converter) and I need to implement

public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

method.

I have to read first property first to determine "target type" R, and then I want to pass whole JSON string to regular generic JsonConverter<R>(string json).

My problem is that I can't read two times from Utf8JsonReader and I can't find any method to read it as text.

Can I read all JSON and store it in some string buffer, so I can read it more than one time?

Yes, I know this will reduce performance a lot.

Kamil
  • 13,363
  • 24
  • 88
  • 183
  • You could preload into a `JsonDocument`, query the type parameter, then deserialize from the `JsonDocument`. See [this answer specifically](https://stackoverflow.com/a/59785679/3744182) to [Is polymorphic deserialization possible in System.Text.Json?](https://stackoverflow.com/q/58074304/3744182). Incidentally, deserializing from a `byte []` buffer will be faster than from a string, see [System.Text.Json.JsonElement ToObject workaround](https://stackoverflow.com/a/59047063/3744182). – dbc Nov 03 '20 at 06:48
  • Do those two questions also answer yours? – dbc Nov 04 '20 at 15:18
  • 1
    @dbc Yes, thanks. Reading everything to `JsonDocument` will do the job. Actually I'm working on polymorphic deserialization too. Why did you put this in comment? – Kamil Nov 04 '20 at 19:40
  • Because I recall you had asked some other question about polymorphic deserialization a few days ago. – dbc Nov 04 '20 at 19:46
  • 1
    @dbc I remember your comment. I followed one of suggestions from that thread about polymorphic deserialization, but I haven't read all answers. Sorry for bugging you by being lazy and not reading whole thread ;) – Kamil Nov 04 '20 at 20:19

0 Answers0