[英]How to convert uint8_t from uart_read_bytes to a char or something that can be added to cJSON object?
[英]How to translate between cJSON and protobuf bytes variable
我正在使用protobuf-c庫和cJSON,並且有protobuf消息,其字段字節為args = 1; //特定於命令的有效負載
我正在將cJSON解析為protobuf,如下所示:
args = cJSON_GetObjectItemCaseSensitive(command, "args");
if (args) {
cJSON_ArrayForEach(arg, args) {
key = arg->string;
log_debug("PARSER: key = %s", key);
if (key != NULL) {
if (cJSON_IsNumber(arg)) {
log_info("received argument: %s : (int)%d : (double)%.2f",
key, arg->valueint, arg->valuedouble);
} else if (cJSON_IsString(arg) && (arg->valuestring != NULL)) {
log_info("received argument: %s : %s", key,
arg->valuestring);
} else {
log_error("error while parsing argument's value");
}
} else {
log_error("error while parsing argument");
}
}
log_debug("PARSER: print = %s", args);
// not sure if it is proper way of adding cJSON object to protobuf's bytes variable
req->args.data = cJSON_Print(args);
req->args.len = strlen(req->args.data);
然后我嘗試將其解析回cJSON並添加為正確的消息格式:
char rpt_char[MAX_RPT_SIZE];
strncpy(rpt_char, (char*)cvp->args.data, cvp->args.len);
cJSON_AddItemToObject(json_message, "rpt", rpt = cJSON_CreateObject());
cJSON_AddStringToObject(rpt, "args", rpt_char);
我需要將消息從cJSON解析到protobuf,然后再返回到cJSON。 最終的JSON應該如下所示:
{
...
rpt: {
arg1: data, // don't know actual names of key strings and values
arg2: data
},
...
}
但是我得到的是:
{
...
"rpt": {
"args": "{\n\t\"arg1\":\t38,\n\t\"arg2\":\t\"Taylor Norman\"\n}[\u0002\u00106[\u0002\u0010�[\u0002\u0010�[\u0002\u0010�ȍ\u0003\u0001�[\u0002\u0010�ȍ\u0006"
},
...
}
編輯。 一些隨機生成器生成的示例消息:
{"cmd":0,"t":963205,"xi":"5d2c8cb34888fc8471991545","args":{"arg1":38,"arg2":"Taylor Norman"},"kid":"5d2c8cb3329f9599e4730b6a","sig":"5d2c8cb33949d35fb22d0cb3"}
我已經為這個任務苦苦掙扎了大約2天,當我發布此主題時,一個燈泡出現在我的頭上...
所以我將翻譯從json略微更改為protobuf:
json = cJSON_PrintUnformatted(args);
req->args.data = json;
req->args.len = strlen(json);
然后我做了類似的事情,從json-> protobuf到protobuf-> json:
args = cJSON_Parse((char*)cvp->args.data);
cJSON_AddItemToObject(json_message, "rpt", args);
if (args) {
cJSON_ArrayForEach(arg, args) {
key = arg->string;
log_debug("PARSER: key = %s", key);
if (key != NULL) {
if (cJSON_IsNumber(arg)) {
log_info("received argument: %s : (int)%d : (double)%.2f",
key, arg->valueint, arg->valuedouble);
cJSON_AddItemToObject(rpt, key, arg->valueint);
} else if (cJSON_IsString(arg) && (arg->valuestring != NULL)) {
log_info("received argument: %s : %s", key,
arg->valuestring);
cJSON_AddItemToObject(rpt, key, arg->valuestring);
} else {
log_error("error while parsing argument's value");
}
} else {
log_error("error while parsing argument");
}
}
}
基本上,結果是我忘記了cJSON_Parse()函數的存在...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.