1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef SECURITY_GUARD_JSON_CFG_H
17 #define SECURITY_GUARD_JSON_CFG_H
18 
19 #include "nlohmann/json.hpp"
20 
21 namespace OHOS::Security::SecurityGuard {
22 #define JSON_CHECK_HELPER_RETURN_IF_FAILED(json, key, type, code) \
23     do { \
24         if ((json).find((key)) == (json).end()) { \
25             return (code); \
26         } \
27         if (!(json).at((key)).is_##type()) { \
28             return (code); \
29         } \
30     } while (0)
31 
32 class JsonCfg {
33 public:
34     static bool Unmarshal(uint64_t &data, nlohmann::json jsonObj, std::string key);
35     static bool Unmarshal(int64_t &data, nlohmann::json jsonObj, std::string key);
36     static bool Unmarshal(uint32_t &data, nlohmann::json jsonObj, std::string key);
37     static bool Unmarshal(int32_t &data, nlohmann::json jsonObj, std::string key);
38     static bool Unmarshal(std::string &data, nlohmann::json jsonObj, std::string key);
39     static bool Unmarshal(std::vector<int32_t> &data, nlohmann::json jsonObj, std::string key);
40     static bool Unmarshal(std::vector<std::string> &data, nlohmann::json jsonObj, std::string key);
41     static bool Unmarshal(std::vector<int64_t> &data, nlohmann::json jsonObj, std::string key);
42     template<typename T>
Unmarshal(T & data,nlohmann::json jsonObj,std::string key)43     static bool Unmarshal(T &data, nlohmann::json jsonObj, std::string key)
44     {
45         JSON_CHECK_HELPER_RETURN_IF_FAILED(jsonObj, key, object, false);
46         data = jsonObj.at(key).get<T>();
47         return true;
48     }
49 
50     template<typename T>
Unmarshal(std::vector<T> & data,nlohmann::json jsonObj,std::string key)51     static bool Unmarshal(std::vector<T> &data, nlohmann::json jsonObj, std::string key)
52     {
53         JSON_CHECK_HELPER_RETURN_IF_FAILED(jsonObj, key, array, false);
54         nlohmann::json arrays = jsonObj.at(key);
55         for (const auto &element : arrays) {
56             if (!element.is_object()) {
57                 return false;
58             }
59             data.emplace_back(element.get<T>());
60         }
61         return true;
62     }
63 
64 private:
65     JsonCfg() = default;
66 };
67 } // namespace OHOS::Security::SecurityGuard
68 
69 #endif // SECURITY_GUARD_JSON_CFG_H
70