Had a badly formed json string that I tried to parse and threw exception causing reset. Is there a method to catch this kind of stuff?
Attempted to try-catch but couldn't get that to work.
Method to catch ill-formed json string with cJSON_Parse
-
- Posts: 90
- Joined: Sun Jul 02, 2017 3:38 am
Re: Method to catch ill-formed json string with cJSON_Parse
Do you know what is ill-formed in your JSON string?
Re: Method to catch ill-formed json string with cJSON_Parse
I was missing a bracket { - Easily fixed.
I was trying to figure out a generic method so that I can confirm I have a valid json before trying to parse, or catching an error when I do parse.
I was trying to figure out a generic method so that I can confirm I have a valid json before trying to parse, or catching an error when I do parse.
-
- Posts: 90
- Joined: Sun Jul 02, 2017 3:38 am
Re: Method to catch ill-formed json string with cJSON_Parse
cJSON_Parse should return 0 on a failed parse. Did you check it’s return value?
Re: Method to catch ill-formed json string with cJSON_Parse
Though I tried that. Here is what I did...
std::string json_str = "{\"name\":\"Johnny\", \"age\":30, \"city\":\"New York\"}";
ESP_LOGD(TAG, "json parse : %d\n", (int)cJSON_Parse(text.c_str()));
return JsonObject(cJSON_Parse(text.c_str()));
when I executed this, json parse : 1073525068
modified the string to: std::string json_str = "\"name\":\"Johnny\", \"age\":30, \"city\":\"New York\"}";
(removed the initial {)
when I executed this, json parse : 1073525068
std::string json_str = "{\"name\":\"Johnny\", \"age\":30, \"city\":\"New York\"}";
ESP_LOGD(TAG, "json parse : %d\n", (int)cJSON_Parse(text.c_str()));
return JsonObject(cJSON_Parse(text.c_str()));
when I executed this, json parse : 1073525068
modified the string to: std::string json_str = "\"name\":\"Johnny\", \"age\":30, \"city\":\"New York\"}";
(removed the initial {)
when I executed this, json parse : 1073525068
-
- Posts: 90
- Joined: Sun Jul 02, 2017 3:38 am
Re: Method to catch ill-formed json string with cJSON_Parse
In both those cases, cJSON_Parse didn’t crash (they successfully returned), so what did?
Re: Method to catch ill-formed json string with cJSON_Parse
You are correct. The exception is occurring when I attempt to perform an action after the parse. The error happens when node->valuestring is called because node=nullptr. So, I can catch the error here. Thanks for the help...
cJSON *node = cJSON_GetObjectItem(m_node, name.c_str());
ESP_LOGD(TAG, "json getString\n");
if(node == nullptr) ESP_LOGD(TAG, "json getString null pointer\n");
return std::string(node->valuestring);
cJSON *node = cJSON_GetObjectItem(m_node, name.c_str());
ESP_LOGD(TAG, "json getString\n");
if(node == nullptr) ESP_LOGD(TAG, "json getString null pointer\n");
return std::string(node->valuestring);
Who is online
Users browsing this forum: Google [Bot] and 110 guests