1 /*
2 * Copyright (c) 2023 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 #include "json_utils.h"
16
17 #include <fstream>
18 #include <sstream>
19
20 #include "log.h"
21
22 namespace OHOS {
23 namespace AppFileService {
24
GetJsonObjFromPath(nlohmann::json & jsonObj,const std::string & jsonPath)25 int32_t JsonUtils::GetJsonObjFromPath(nlohmann::json& jsonObj, const std::string& jsonPath)
26 {
27 std::ifstream jsonFileStream;
28 jsonFileStream.open(jsonPath.c_str(), std::ios::in);
29 if (!jsonFileStream.is_open()) {
30 LOGE("Open json file path %{public}s failed with error %{public}d", jsonPath.c_str(), errno);
31 return -errno;
32 }
33
34 std::ostringstream buf;
35 char ch;
36 while (buf && jsonFileStream.get(ch)) {
37 buf.put(ch);
38 }
39 jsonFileStream.close();
40
41 jsonObj = nlohmann::json::parse(buf.str(), nullptr, false);
42 if (jsonObj.is_discarded()) {
43 LOGE("Parse json file path %{public}s failed", jsonPath.c_str());
44 }
45 return 0;
46 }
47
GetKVFromJson(const nlohmann::json & json,const std::string & key,std::string & value)48 int32_t JsonUtils::GetKVFromJson(const nlohmann::json &json, const std::string &key,
49 std::string &value)
50 {
51 if (!json.is_object()) {
52 LOGE("Invalid json object");
53 return -EINVAL;
54 }
55
56 bool ret = json.find(key) != json.end() && json.at(key).is_string();
57 if (ret) {
58 value = json.at(key).get<std::string>();
59 return 0;
60 } else {
61 return -EINVAL;
62 }
63 }
64
65 } // AppFileService
66 } // OHOS