#include #include #include #include #include "fastjson/core.h" #include "fastjson/dom.h" struct Address { std::string name; std::string address; std::map phone_numbers; }; struct AddressBook { std::vector
addresses; }; namespace fastjson { namespace dom { template<> struct json_helper { static bool build( Token * tok, Chunk * chunk , const AddressBook & value ) { return json_helper >::build(tok,chunk,value.addresses); } static bool from_json_value( const Token * token, AddressBook * book ) { if( ! book ) return false; return json_helper >::from_json_value(token, &book->addresses ); } }; template<> struct json_helper
{ static bool build( Token * tok, Chunk * chunk , const Address & value ) { Dictionary dict = Dictionary::create_dict(tok,chunk); dict.add( "name", value.name ); dict.add( "address", value.address ); dict.add >( "phone", value.phone_numbers ); return true; } static bool from_json_value( const Token * token, Address * address ) { if(!token) return false; if(!address) return false; Dictionary_const dict = Dictionary_const::as_dict(token); if( ! dict.get("name",&address->name) ) return false; if( ! dict.get("address",&address->address) ) return false; if( ! dict.get >("phone",&address->phone_numbers) ) return false; return true; } }; template<> struct json_helper< std::map > { static bool build( Token * tok, Chunk * chunk , const std::map & value ) { Dictionary dict = Dictionary::create_dict(tok,chunk); for( std::map::const_iterator it = value.begin(); it!=value.end(); ++it ) { dict.add( it->first, it->second ); } return true; } static bool from_json_value( const Token * token, std::map * value ) { if(!token) return false; if(!value) return false; if( token->type != Token::DictToken ) return false; DictEntry * e = token->dict.ptr; while( e ) { std::string k; std::string v; //NOTE: We're not failing if we can't convert a key pair, we're just ignoring it. if( json_helper::from_json_value( &e->key_tok, &k ) && json_helper::from_json_value( &e->value_tok, &v ) ) { (*value)[k]=v; } e = e->next; } return true; } }; } } void on_json_error( void *, const fastjson::ErrorContext& ec) { std::cerr<<"ERROR: "<::from_json_value( &root, book ); return true; } bool write_address_book( AddressBook * book, const std::string & filename ) { std::ofstream f( filename.c_str(), std::ios::binary ); if(!f) { std::cerr<<"Unable to open file \""<::build(&token,&chunk,*book); //Write to file f<