C语言使用Cjson库解析一下json串{ "message":"", "reason":"", "res":{ "deviceInfo":null, "iotMqttInfo":null, "status":"NOTFOUND" }
时间: 2023-09-02 08:08:51 浏览: 97
以下是使用Cjson库解析该json串的代码示例:
```c
#include <stdio.h>
#include <string.h>
#include "cJSON.h"
int main()
{
// 定义要解析的json串
const char* json_str = "{ \"message\":\"\", \"reason\":\"\", \"res\":{ \"deviceInfo\":null, \"iotMqttInfo\":null, \"status\":\"NOTFOUND\" } }";
// 解析json串
cJSON* root = cJSON_Parse(json_str);
// 获取message字段的值
cJSON* message = cJSON_GetObjectItem(root, "message");
if (message != NULL)
{
printf("message: %s\n", message->valuestring);
}
// 获取reason字段的值
cJSON* reason = cJSON_GetObjectItem(root, "reason");
if (reason != NULL)
{
printf("reason: %s\n", reason->valuestring);
}
// 获取res字段的值
cJSON* res = cJSON_GetObjectItem(root, "res");
if (res != NULL)
{
// 获取deviceInfo字段的值
cJSON* deviceInfo = cJSON_GetObjectItem(res, "deviceInfo");
if (deviceInfo == NULL || cJSON_IsNull(deviceInfo))
{
printf("deviceInfo: null\n");
}
// 获取iotMqttInfo字段的值
cJSON* iotMqttInfo = cJSON_GetObjectItem(res, "iotMqttInfo");
if (iotMqttInfo == NULL || cJSON_IsNull(iotMqttInfo))
{
printf("iotMqttInfo: null\n");
}
// 获取status字段的值
cJSON* status = cJSON_GetObjectItem(res, "status");
if (status != NULL)
{
printf("status: %s\n", status->valuestring);
}
}
// 释放内存
cJSON_Delete(root);
return 0;
}
```
运行结果为:
```
message:
reason:
deviceInfo: null
iotMqttInfo: null
status: NOTFOUND
```
阅读全文