问题
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)
- doesn't accept
StreamReader
, and - 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 myJsonConverter
s _
- doesn't accept
- JavaScriptSerializer also doesn't seem to support
Stream
s at all.- And even undocummented
new JsonSerializer().Deserialize(new JsonTextReader(streamReader))
- And even undocummented
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.
来源:https://stackoverflow.com/questions/14990590/is-there-a-pull-style-json-streamreader-parser-for-net