• 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 #include "json_utils.h"
17 #include "appspawn_server.h"
18 
19 #include <sstream>
20 #include <fstream>
21 
22 using namespace std;
23 using namespace OHOS;
24 
25 namespace OHOS {
26 namespace AppSpawn {
GetJsonObjFromJson(nlohmann::json & jsonObj,const std::string & jsonPath)27 bool JsonUtils::GetJsonObjFromJson(nlohmann::json &jsonObj, const std::string &jsonPath)
28 {
29     APPSPAWN_CHECK(jsonPath.length() <= PATH_MAX, return false, "jsonPath is too long");
30     std::ifstream jsonFileStream;
31     jsonFileStream.open(jsonPath.c_str(), std::ios::in);
32     APPSPAWN_CHECK(jsonFileStream.is_open(), return false, "Open json file failed.");
33     std::ostringstream buf;
34     char ch;
35     while (buf && jsonFileStream.get(ch)) {
36         buf.put(ch);
37     }
38     jsonFileStream.close();
39     jsonObj = nlohmann::json::parse(buf.str(), nullptr, false);
40     APPSPAWN_CHECK(jsonObj.is_structured(), return false, "Parse json file into jsonObj failed.");
41     return true;
42 }
43 
GetStringFromJson(const nlohmann::json & json,const std::string & key,std::string & value)44 bool JsonUtils::GetStringFromJson(const nlohmann::json &json, const std::string &key, std::string &value)
45 {
46     APPSPAWN_CHECK(json.is_object(), return false, "json is not object.");
47     bool isRet = json.find(key) != json.end() && json.at(key).is_string();
48     APPSPAWN_CHECK(!isRet, value = json.at(key).get<std::string>();
49         return true, "Find key[%s] successful.", key.c_str());
50     return false;
51 }
52 } // namespace AppSpawn
53 } // namespace OHOS