2 * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
4 * Contact: Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com)
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License
21 * @author Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com)
25 #ifndef CONFIG_TO_JSON_VISITOR_HPP
26 #define CONFIG_TO_JSON_VISITOR_HPP
28 #include "config/is-visitable.hpp"
30 #include <json/json.h>
40 : mObject(json_object_new_object())
44 ToJsonVisitor(const ToJsonVisitor& visitor)
45 : mObject(json_object_get(visitor.mObject))
51 json_object_put(mObject);
54 ToJsonVisitor& operator=(const ToJsonVisitor&) = delete;
56 std::string toString() const
58 return json_object_to_json_string(mObject);
62 void visit(const std::string& name, const T& value)
64 json_object_object_add(mObject, name.c_str(), toJsonObject(value));
72 json_object* ret = mObject;
77 static json_object* toJsonObject(int value)
79 return json_object_new_int(value);
82 static json_object* toJsonObject(std::int64_t value)
84 return json_object_new_int64(value);
87 static json_object* toJsonObject(bool value)
89 return json_object_new_boolean(value);
92 static json_object* toJsonObject(double value)
94 return json_object_new_double(value);
97 static json_object* toJsonObject(const std::string& value)
99 return json_object_new_string(value.c_str());
103 static json_object* toJsonObject(const std::vector<T>& value)
105 json_object* array = json_object_new_array();
106 for (const T& v : value) {
107 json_object_array_add(array, toJsonObject(v));
112 template<typename T, class = typename std::enable_if<isVisitable<T>::value>::type>
113 static json_object* toJsonObject(const T& value)
115 ToJsonVisitor visitor;
116 value.accept(visitor);
117 return visitor.detach();
121 } // namespace config
123 #endif // CONFIG_TO_JSON_VISITOR_HPP