how to handle the error in cJSON
vinothkrstatiq opened this issue · 1 comments
vinothkrstatiq commented
const char *a1 = "[2,"531531531","BootNotification",{"chargePointModel":"Smartplug2.0","chargePointVendor":"Statiq"}]";
const char *a2 = "[3,"af2e620d-8571-49f0-b3c2-0144c2b4f9bf",{"currentTime":"2022-05-25T17:38:45.311043","interval":10,"status":"Accepted"}]";
cJSON *root = cJSON_Parse(nn);
JSON_Analyze(root);
cJSON *e1 = cJSON_GetArrayItem(root, 0);
if(e1 != NULL) {
printf(" id %d \n", e1->valueint);
}
cJSON *e2 = cJSON_GetArrayItem(root, 1);
if(e2 != NULL) {
printf(" id %s \n", e2->valuestring);
}
cJSON *e3 = cJSON_GetArrayItem(root, 2);
if(e3 != NULL) {
printf(" id %s \n", e3->valuestring);
}
cJSON *e4 = cJSON_GetArrayItem(root, 3);
cJSON *e41 = cJSON_GetObjectItem(e4, "chargePointModel");
if(e41 != NULL) {
printf(" id %s \n", e41->valuestring);
}
cJSON *e42 = cJSON_GetObjectItem(e4, "chargePointVendor");
if(e42 != NULL) {
printf(" id %s \n", e42->valuestring);
}
cJSON_Delete(root);
In the above example if I use const char *a1 it will work properly
if I use const char *a2 it will crash
how to handle this error ? I don't want my code to crash .
is there any function to check the error ??
nopnop2002 commented
a1 have 4 array element.
a2 have 3 array element.
The solution is to find the number of elements contained in the array.
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "cJSON.h"
static const char *TAG = "JSON";
void app_main()
{
const char * a1 = "[2,\"531531531\",\"BootNotification\",{\"chargePointModel\":\"Smartplug2.0\",\"ChargePointVendor\":\"Statiq\"}]";
const char * a2 = "[3,\"af2e620d-8571-49f0-b3c2-0144c2b4f9bf\",{\"currentTime\":\"2022-05-25T17:38:45.311043\",\"interval\":10,\"status\":\"Accepted\"}]";
cJSON *root1 = cJSON_Parse(a1);
ESP_LOGI(TAG, "cJSON_GetArraySize(a1)=%d",cJSON_GetArraySize(root1));
cJSON *root2 = cJSON_Parse(a2);
ESP_LOGI(TAG, "cJSON_GetArraySize(a2)=%d",cJSON_GetArraySize(root2));
cJSON_Delete(root1);
cJSON_Delete(root2);
}
I (327) JSON: cJSON_GetArraySize(a1)=4
I (337) JSON: cJSON_GetArraySize(a2)=3