1 /*
2 * Copyright (C) 2024 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 JSON_UTILS_H
17 #define JSON_UTILS_H
18
19 #include <stdbool.h>
20
21 #include "appspawn_utils.h"
22 #include "cJSON.h"
23
24 #ifdef __cplusplus
25 extern "C" {
26 #endif // __cplusplus
27
28 #define MAX_JSON_FILE_LEN 102400
29 typedef struct TagParseJsonContext ParseJsonContext;
30 typedef int (*ParseConfig)(const cJSON *root, ParseJsonContext *context);
31 int ParseJsonConfig(const char *path, const char *fileName, ParseConfig parseConfig, ParseJsonContext *context);
32 cJSON *GetJsonObjFromFile(const char *jsonPath);
33
GetStringFromJsonObj(const cJSON * json,const char * key)34 __attribute__((always_inline)) inline char *GetStringFromJsonObj(const cJSON *json, const char *key)
35 {
36 APPSPAWN_CHECK_ONLY_EXPER(key != NULL && json != NULL, NULL);
37 APPSPAWN_CHECK(cJSON_IsObject(json), return NULL, "json is not object %{public}s %s", key, cJSON_Print(json));
38 cJSON *obj = cJSON_GetObjectItemCaseSensitive(json, key);
39 APPSPAWN_CHECK_ONLY_EXPER(obj != NULL, return NULL);
40 APPSPAWN_CHECK(cJSON_IsString(obj), return NULL, "json is not string %{public}s %s", key, cJSON_Print(obj));
41 return cJSON_GetStringValue(obj);
42 }
43
GetBoolValueFromJsonObj(const cJSON * json,const char * key,bool def)44 __attribute__((always_inline)) inline bool GetBoolValueFromJsonObj(const cJSON *json, const char *key, bool def)
45 {
46 char *value = GetStringFromJsonObj(json, key);
47 APPSPAWN_CHECK_ONLY_EXPER(value != NULL, return def);
48
49 if (strcmp(value, "true") == 0 || strcmp(value, "ON") == 0 || strcmp(value, "True") == 0) {
50 return true;
51 }
52 return false;
53 }
54
GetIntValueFromJsonObj(const cJSON * json,const char * key,uint32_t def)55 __attribute__((always_inline)) inline uint32_t GetIntValueFromJsonObj(const cJSON *json, const char *key, uint32_t def)
56 {
57 APPSPAWN_CHECK(json != NULL, return def, "Invalid json");
58 APPSPAWN_CHECK(cJSON_IsObject(json), return def, "json is not object.");
59 return cJSON_GetNumberValue(cJSON_GetObjectItemCaseSensitive(json, key));
60 }
61
62 #ifdef __cplusplus
63 }
64 #endif // __cplusplus
65 #endif // JSON_UTILS_H