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
16 #include "JsonReader.h"
17
18 #include <fstream>
19
20 #include "PreviewerEngineLog.h"
21 #include "json.h"
22
23 using namespace std;
ReadFile(const string path)24 string JsonReader::ReadFile(const string path)
25 {
26 ifstream inFile(path);
27 if (!inFile.is_open()) {
28 ELOG("JsonReader: Open json file failed.");
29 return string();
30 }
31 string jsonStr((istreambuf_iterator<char>(inFile)), istreambuf_iterator<char>());
32 inFile.close();
33 return jsonStr;
34 }
35
ParseJsonData(const string jsonStr)36 Json::Value JsonReader::ParseJsonData(const string jsonStr)
37 {
38 Json::Value val;
39 Json::CharReaderBuilder builder;
40 Json::CharReader* charReader = builder.newCharReader();
41 if (charReader == nullptr) {
42 ELOG("JsonReader: CharReader memory allocation failed.");
43 return val;
44 }
45 std::unique_ptr<Json::CharReader> reader(charReader);
46 if (reader.get() == nullptr) {
47 ELOG("JsonReader: CharReader get null.");
48 return val;
49 }
50 string message; // NOLINT
51 if (!reader->parse(jsonStr.data(), jsonStr.data() + jsonStr.size(), &val, &message)) {
52 ELOG("JsonReader: Failed to parse the json data, errors: %s", message.c_str());
53 }
54 return val;
55 }
56