• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     template<typename T>
Unmarshal(T & data,nlohmann::json jsonObj,std::string key)42     static bool Unmarshal(T &data, nlohmann::json jsonObj, std::string key)
43     {
44         JSON_CHECK_HELPER_RETURN_IF_FAILED(jsonObj, key, object, false);
45         data = jsonObj.at(key).get<T>();
46         return true;
47     }
48 
49     template<typename T>
Unmarshal(std::vector<T> & data,nlohmann::json jsonObj,std::string key)50     static bool Unmarshal(std::vector<T> &data, nlohmann::json jsonObj, std::string key)
51     {
52         JSON_CHECK_HELPER_RETURN_IF_FAILED(jsonObj, key, array, false);
53         nlohmann::json arrays = jsonObj.at(key);
54         for (const auto &element : arrays) {
55             if (!element.is_object()) {
56                 return false;
57             }
58             data.emplace_back(element.get<T>());
59         }
60         return true;
61     }
62 
63 private:
64     JsonCfg() = default;
65 };
66 } // namespace OHOS::Security::SecurityGuard
67 
68 #endif // SECURITY_GUARD_JSON_CFG_H
69