1- // Copyright (c) 2015- 2016 Dr. Colin Hirsch and Daniel Frey
1+ // Copyright (c) 2016 Dr. Colin Hirsch and Daniel Frey
22// Please see LICENSE for license or visit https://github.com/taocpp/json/
33
44#include " test.hh"
@@ -11,7 +11,7 @@ namespace tao
1111 {
1212 namespace
1313 {
14- // SAX consumer to build a NLohmann/JSON value
14+ // SAX consumer to build an nlohmann/json value
1515 class to_nlohmann
1616 {
1717 private:
@@ -102,6 +102,51 @@ namespace tao
102102 }
103103 };
104104
105+ // SAX producer for an nlohmann/json value
106+ template < typename Handler >
107+ void traverse_nlohmann ( const nlohmann::json & v, Handler & handler )
108+ {
109+ switch ( v.type () ) {
110+ case nlohmann::json::value_t ::null:
111+ handler.null ();
112+ break ;
113+ case nlohmann::json::value_t ::boolean:
114+ handler.boolean ( v.get < bool >() );
115+ break ;
116+ case nlohmann::json::value_t ::number_integer:
117+ handler.number ( v.get < std::int64_t >() );
118+ break ;
119+ case nlohmann::json::value_t ::number_unsigned:
120+ handler.number ( v.get < std::uint64_t >() );
121+ break ;
122+ case nlohmann::json::value_t ::number_float:
123+ handler.number ( v.get < double >() );
124+ break ;
125+ case nlohmann::json::value_t ::string:
126+ handler.string ( v.get_ref < const std::string & >() );
127+ break ;
128+ case nlohmann::json::value_t ::array:
129+ handler.begin_array ();
130+ for ( const auto & e : v ) {
131+ traverse_nlohmann ( e, handler );
132+ handler.element ();
133+ }
134+ handler.end_array ();
135+ break ;
136+ case nlohmann::json::value_t ::object:
137+ handler.begin_object ();
138+ for ( nlohmann::json::const_iterator it = v.begin (); it != v.end (); ++it ) {
139+ handler.key ( it.key () );
140+ traverse_nlohmann ( it.value (), handler );
141+ handler.member ();
142+ }
143+ handler.end_object ();
144+ break ;
145+ default :
146+ throw std::logic_error ( " invalid value for nohmann::json::type()" ); // LCOV_EXCL_LINE
147+ }
148+ }
149+
105150 } //
106151
107152 void unit_test ()
@@ -129,6 +174,12 @@ namespace tao
129174 TEST_ASSERT ( v[ 7 ].size () == 2 );
130175 TEST_ASSERT ( v[ 7 ].at ( " a" ) == " b" );
131176 TEST_ASSERT ( v[ 7 ].at ( " c" ) == " d" );
177+
178+ std::ostringstream oss;
179+ sax::to_stream oss_handler ( oss );
180+ traverse_nlohmann ( v, oss_handler );
181+
182+ TEST_ASSERT ( oss.str () == " [null,true,false,42,43.0,\" foo\" ,[1,2,3],{\" a\" :\" b\" ,\" c\" :\" d\" }]" );
132183 }
133184
134185 } // json
0 commit comments