$darkmode
with_boost.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 Robert Bosch GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * SPDX-License-Identifier: Apache-2.0
17  */
26 #pragma once
27 #ifndef FABLE_JSON_WITH_BOOST_HPP_
28 #define FABLE_JSON_WITH_BOOST_HPP_
29 
30 #include <nlohmann/json.hpp>
31 
32 #include <boost/optional.hpp>
33 
34 /*
35  * In order to provide serialization for third-party types, we need to either
36  * use their namespace or provide a specialization in that of nlohmann. It is
37  * illegal to define anything in the std namespace, so we are left no choice in
38  * this regard.
39  *
40  * See: https://github.com/nlohmann/json
41  */
42 namespace nlohmann {
43 
44 template <typename T>
45 struct adl_serializer<boost::optional<T>> {
46  static void to_json(json& j, const boost::optional<T>& opt) {
47  if (opt) {
48  j = *opt;
49  } else {
50  j = nullptr;
51  }
52  }
53 
54  static void from_json(const json& j, boost::optional<T>& opt) {
55  if (j.type() == json::value_t::null) {
56  opt.reset();
57  } else {
58  *opt = j.get<T>();
59  }
60  }
61 };
62 
63 } // namespace nlohmann
64 
65 #endif // FABLE_JSON_WITH_BOOST_HPP_
Definition: conf.hpp:64
Definition: confable.hpp:132