Tencent / rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API
http://rapidjson.org/
Other
14.24k stars 3.54k forks source link

Nested objects with SAX #332

Closed joostmeijles closed 8 years ago

joostmeijles commented 9 years ago

Hi,

As far as I understand the way to handle nested objects using the SAX parser is to maintain state variables in the handler that is passed to the Reader. This handler than forwards events based on the current state. The disadvantage of this approach is that I have to write quite some boilerplate, and have to manage quite some state (I have to take state of embedded objects into account).

Would it be possible to simplify the use of nested objects by switching the active handler upon StartObject() and switch it back to the parent on EndObject()?

Kind regards, Joost

miloyip commented 9 years ago

You may create a "delegate" handler which delegates events to a polymorphic handler class (the one with virtual functions). And then you can switch the handler dynamically at the "delegate" handler. Basically, to implement an unlimited depth of handler, you will need a stack data structure to keep-track the current traversal state.

I think providing some examples may help on this. I will try to, or you may contribute one if you solved your problem.

joostmeijles commented 9 years ago

Ah, indeed. That's a good way to solve it, thanks!

samunns commented 8 years ago

Are there any examples on how to use handlers? I read in your "http://rapidjson.org/md_doc_dom.html" that "User may create custom handlers for transforming the DOM into other formats. For example, a handler which converts the DOM into XML." Since I am fairly new to C++ and using your code I was wondering if any examples exist that might help me illustrate how to write such a handler?

miloyip commented 8 years ago

An example jsonx is added recently. It is a handler to create XML from SAX events. You can use this to convert a DOM to XML as well.