Re: [Cppcms-users] CppCMS 1.x.x JSON object value empty/not exist
Brought to you by:
artyom-beilis
From: Artyom <art...@ya...> - 2010-06-16 09:26:31
|
> > I can't use the json rpc server since I have a requirement > for a > RESTlike architecture. It requires the use of several HTTP > methods > beyond GET and POST. I also require using the PUT, DELETE > & OPTIONS > methods. > So I'll will be making a json_rpc_server like class for > handling this > with a custom dispatching system for handling different > http methods. I just suggested, of course you do what you need. > > I have another small question regarding the conversion > between C++ and > json objects. How do I do this for custom objects? If I am > correct this > should be possible by implementing a custom struct > traits<T>? Could you > give an example on how to do this? First take a look in cppcms/json.h file there are some specializations for std::vector, std::map, std::pair and some other basic strings they would give you a clue how to start All you need to implement get and set static members: For example (I hadn't tested this code): struct person { std::string name; double salary; std::vector<std::string> kids_names; }; namespace cppcms { namespace json { template<> struct traits<person> { static person get(value const &v) { person p; if(v.object().size()!=4) throw bad_value_cast(); p.name=v.get_value<std::string>("name"); p.salary=v.get_value<double>("salary"); p.kids_names= v.get_value<std::vectror<std::string> >("kids_names"); // this works because generic vector and string specialized } static void set(value &v,person const &in) { v.set_value("name",p.name); v.set_value("salary",p.salary); v.set_value("kids_names",p.kids_names); } }; } // json } // cppcms Note1: By convention, faults in conversion should throw bad_value_cast so some functions can catch them and substitute with defaults if needed. Note2: current internal HTTP Server supports GET, POST and HEAD requests, so you need to work via FastCGI or SCGI API behind the browser. I can add support of PUT and DELETE just tell if you need. But remember that you should not use internal HTTP server for production environment as it build for debugging purposes. You may probably use it in trusted environment as it does not do too much security checks. Artyom |