Search code examples
c++jsonrapidjson

How to write a nested handler for rapidjson deserialization?


I'd like to write a nested handler for consumption of json using rapidjson.

I've modeled my basic handler along the lines of the official simplereader example. This is fine for flat structures, but now I need to expand the parsing to nested objects as well.

The way I see it, I can either

  1. have a central handler that keeps track of various domain objects to create and subsequent parse values into, or
  2. I can change handler while parsing

Technically, I know how to do 1., but 2. seems like a neater solution, if possible.

Is it possible to change handlers mid-stream? Is there a best practice for doing this?

Thanks!


Solution

  • You can delegate the events to other handlers. This is often done by:

    1. Applying the State Pattern internally in your custom handler. So that the handler can delegate the events to the current state object via polymorphism (a.k.a. virtual functions).

    2. Using switch-case to do the delegation with an enum.

    The first one has advantage if you need to deal with recursive structure. You can push the pointers of state objects in a stack.