- int JsonTable::encode_to_string(const JsonObj* obj, char* buf, int buf_size)
- {
- TRACE_FUNC("JsonTable::encode_to_string");
- const char * ch = (const char*)obj;
- const char * ptr = NULL;
- JsonTable::Lock _guard(this);
- FieldList::Iterator it = _list_fields.begin();
- //skip size of base-struct JsonObj
- ptr = ch + sizeof(JsonObj);
- try {
- if(NULL == obj) {
- throw MyJsonException(MYJSON_NULL, "the pointer of struct JsonObj is NULL");
- }
- if(_json_object) {
- json_object_put(_json_object);
- _json_object = NULL;
- }
- _json_object = json_object_new_object();
- //add table's name to json_object
- json_object_object_add(_json_object,"object_name",json_object_new_string((char*)_tbl_name.c_str()));
- //interator every field defined in table
- //and in order to set value to it
- for(; it != _list_fields.end(); ++it) {
- (*it)->set_value(_json_object, ptr);
- ptr += (*it)->get_filed()->_field_len;
- if((ptr - ch) > obj->_length) {
- throw MyJsonException(MYJSON_LENGTH_ERROR, "the length of struct is not validate");
- }
- }
- ptr = json_object_to_json_string(_json_object);
- XOS::strncpy(buf, ptr, buf_size);
- }catch(const MyJsonException& e) {
- LOG_TRACE(("%d: %s", e.errcode(), e.what()));
- return e.errcode();
- }
- return MYJSON_SUCCESS;
- }
- //该片段来自于http://www.codesnippet.cn/detail/100420132794.html
来源: http://www.codesnippet.cn/detail/100420132794.html