-->

Is there a pull-style JSON StreamReader parser for

2019-05-29 08:14发布

问题:

I need to deserialize from a JSON StreamReader, without instantiating intermediate objects for every object in that stream.

  • JSON.NET invoked like JsonConvert.DeserializeObject<T>(string json, JsonConverter[] converters)
    1. doesn't accept StreamReader, and
    2. creates in memory the whole set of Newtonsoft.Json.* classes for the JSON structore, as memory profiler shows. _I'm not actually sure this is the case, because my JsonConverters _
  • JavaScriptSerializer also doesn't seem to support Streams at all.
    1. And even undocummented new JsonSerializer().Deserialize(new JsonTextReader(streamReader))

What I want in a zero approach is a SAX or StAX-style JSON parser.

What I want ideally, is an API like

object JsonCooler.DeserializeObject<T>(
  StreamReader jsonStream, Converter[] converters)

which will deserialize directly into a new instance of class T, not keeping all of its intermediate DOM-like objects in memory.

Does such a deserializer exist? Or what am I missing at the concept level?

回答1:

I suspect it's a use case becoming more and more frequent. I am considering to support it some time via this little one that I also strive to keep short and fast:

https://github.com/ysharplanguage/FastJsonParser

I'm still busy making it stable first, but if you want to give a try at implementing that in a fork before I get a chance, that'd hopefully be enough to amend slightly the Obj(int outer) and Arr(int outer) methods, along with adding an (optional) "reviver" callback delegate to the TypeInfo cache. That one would allow the application to decide whether/when the next object "{ ... }" or array "[ ... ]" in the stream needs its content be fully deserialized or not.

'HTH,



回答2:

I found a DataReader in LitJSON, but it's pretty dated. Will accept any better answer.