在RTThread里使用cjson软件包解析JSON数据包

rtthread里使用cjson软件包解析JSON的程序,json里面包含:姓名、年龄、身高。

首先,需要头文件:#include "cjson.h"。然后,使用 cJSON *cJSON_Parse(const char *value) 来解析一个 JSON 字符串,并返回一个 cJSON 结构体。现在可以使用它来读取姓名,年龄,身高信息:

// Get the name
cJSON *name = cJSON_GetObjectItem(root, "name");
if (name != NULL) {
    printf("Name: %s\n", name->valuestring);
}

// Get the age
cJSON *age = cJSON_GetObjectItem(root, "age");
if (age != NULL) {
    printf("Age: %d\n", age->valueint);
}

// Get the height
cJSON *height = cJSON_GetObjectItem(root, "height");
if (height != NULL) {
    printf("Height: %f\n", height->valuedouble);
}

解析这个数据包:

{
"tid":"tid123",
 "key": "key123",
 "userName": "name123",
 "password": 123,
 "ip": "1.1.1.1",
 "port": 123,
 "mountPoint": 123
}

首先,需要头文件:#include "cjson.h"。然后,使用 cJSON *cJSON_Parse(const char *value) 来解析一个 JSON 字符串,并返回一个 cJSON 结构体。 现在可以使用它来读取 tid、key、serName、password、ip、port、mountPoint 等信息:

// Get the tid
cJSON *tid = cJSON_GetObjectItem(root, "tid");
if (tid != NULL) {
    printf("TID: %s\n", tid->valuestring);
}

// Get the key
cJSON *key = cJSON_GetObjectItem(root, "key");
if (key != NULL) {
    printf("Key: %s\n", key->valuestring);
}

// Get the userName
cJSON *userName = cJSON_GetObjectItem(root, "userName");
if (userName != NULL) {
    printf("User Name: %s\n", userName->valuestring);
}

// Get the password
cJSON *password = cJSON_GetObjectItem(root, "password");
if (password != NULL) {
    printf("Password: %d\n", password->valueint);
}

// Get the ip
cJSON *ip = cJSON_GetObjectItem(root, "ip");
if (ip != NULL) {
    printf("IP: %s\n", ip->valuestring);
}

// Get the port
cJSON *port = cJSON_GetObjectItem(root, "port");
if (port != NULL) {
    printf("Port: %d\n", port->valueint);
}

// Get the mountPoint
cJSON *mountPoint = cJSON_GetObjectItem(root, "mountPoint");
if (mountPoint != NULL) {
    printf("Mount Point: %d\n", mountPoint->valueint);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值