C语言解析{"messageId":"1660564950397","downstream":{"devices":{"start":0,"port":"RS485_0","protocol":"Modbus_RTU_Master"}}}
时间: 2023-10-05 13:09:01 浏览: 60
RS485采集模块与力控软件进行Modbus_RTU通讯
C语言解析的{"messageId":"1660564950397","downstream":{"devices":{"start":0,"port":"RS485_0","protocol":"Modbus_RTU_Master"}}}可以通过使用C语言的JSON解析库来实现。您可以使用类似于cJSON这样的库来解析JSON字符串并提取所需的信息。在这个例子中,您可以通过使用cJSON库来解析messageId、start、port和protocol字段的值。
示例代码如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main() {
const char *json_str = "{\"messageId\":\"1660564950397\",\"downstream\":{\"devices\":{\"start\":0,\"port\":\"RS485_0\",\"protocol\":\"Modbus_RTU_Master\"}}}";
cJSON *json_root = cJSON_Parse(json_str);
if (json_root == NULL) {
printf("Failed to parse JSON!\n");
return 1;
}
cJSON *json_message_id = cJSON_GetObjectItem(json_root, "messageId");
if (json_message_id != NULL) {
printf("messageId: %s\n", json_message_id->valuestring);
}
cJSON *json_downstream = cJSON_GetObjectItem(json_root, "downstream");
if (json_downstream != NULL) {
cJSON *json_devices = cJSON_GetObjectItem(json_downstream, "devices");
if (json_devices != NULL) {
cJSON *json_start = cJSON_GetObjectItem(json_devices, "start");
cJSON *json_port = cJSON_GetObjectItem(json_devices, "port");
cJSON *json_protocol = cJSON_GetObjectItem(json_devices, "protocol");
if (json_start ! NULL) {
printf("start: %d\n", json_start->valueint);
}
if (json_port != NULL) {
printf("port: %s\n", json_port->valuestring);
}
if (json_protocol != NULL) {
printf("protocol: %s\n", json_protocol->valuestring);
}
}
}
cJSON_Delete(json_root);
return 0;
}
```
阅读全文