2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 * Author : Maxim Mamontov <faust@stargazer.dp.ua>
21 #include "stg/json_generator.h"
23 #include <yajl/yajl_gen.h>
25 using STG::JSON::NullGen;
26 using STG::JSON::BoolGen;
27 using STG::JSON::StringGen;
28 using STG::JSON::NumberGen;
29 using STG::JSON::MapGen;
30 using STG::JSON::ArrayGen;
31 using STG::JSON::Callback;
36 void genString(yajl_gen_t* handle, const std::string& value)
38 yajl_gen_string(handle, reinterpret_cast<const unsigned char*>(value.c_str()), value.length());
43 void NullGen::run(yajl_gen_t* handle) const { yajl_gen_null(handle); }
44 void BoolGen::run(yajl_gen_t* handle) const { yajl_gen_bool(handle, m_value); }
45 void StringGen::run(yajl_gen_t* handle) const { genString(handle, m_value); }
46 void NumberGen::run(yajl_gen_t* handle) const { yajl_gen_number(handle, m_value.c_str(), m_value.length()); }
48 void MapGen::run(yajl_gen_t* handle) const
50 yajl_gen_map_open(handle);
51 for (Value::const_iterator it = m_value.begin(); it != m_value.end(); ++it)
53 genString(handle, it->first);
54 it->second.first->run(handle);
56 yajl_gen_map_close(handle);
59 void ArrayGen::run(yajl_gen_t* handle) const
61 yajl_gen_array_open(handle);
62 for (Value::const_iterator it = m_value.begin(); it != m_value.end(); ++it)
63 it->first->run(handle);
64 yajl_gen_array_close(handle);
67 bool STG::JSON::generate(Gen& gen, Callback callback, void* data)
69 yajl_gen handle = yajl_gen_alloc(NULL);
73 const unsigned char* buf = NULL;
75 yajl_gen_get_buf(handle, &buf, &size);
77 bool res = callback(data, reinterpret_cast<const char*>(buf), size);
79 yajl_gen_free(handle);