armink / struct2json

A fast convert library between the JSON and C structure. Implement structure serialization and deserialization for C. | C 结构体与 JSON 快速互转库,快速实现 C 结构体的序列化及反序列化
MIT License
687 stars 295 forks source link

整数转换的结果,打印显示 ld #35

Open DebGith opened 1 year ago

DebGith commented 1 year ago

我将 字符串 和 整数 转换成 json格式,然后用串口发送出去,字符串转换没问题,但整数转换得到的结果,用串口打印 %d 正常,用串口打印 %s 却显示 ld,不知道什么原因造成,而我需要发送的json数据,要能正常显示整数值。 请问如何解决 `

typedef struct { char TestString[10]; int TestInt; }Struct_test;

cJSON struct_to_json_Struct_test(void struct_obj) { s2j_create_json_obj(jsonobj); Struct_test structobj = (Struct_test )struct_obj; s2j_json_set_basic_element(jsonobj, structobj, string, TestString); s2j_json_set_basic_element(jsonobj, structobj, int, TestInt); return jsonobj; }

void json_to_struct_Struct_test(cJSON json_obj) { s2j_create_struct_obj(structobj, Struct_test); s2j_struct_get_basic_element(structobj,json_obj, string, TestString); s2j_struct_get_basic_element(structobj,json_obj, int, TestInt); return structobj; }

int main(void) { static Struct_test _Struct_test = { .TestString = "OK", .TestInt = 123
};

cJSON *p1 = struct_to_json_Struct_test(&_Struct_test);
if(p1 != NULL)
{
    char *p2 = cJSON_Print(p1);
    if(p2 != NULL)
    {
        UartPrint("\nThe Json is:\n%s",p2);

        Struct_test *converted_obj = json_to_struct_Struct_test(p1);

        if (memcmp(&_Struct_test, converted_obj, sizeof(Struct_test)))
        {
            UartPrint("\nConverted failed!\n");
        }
        else
        {
            UartPrint("\nConverted OK!\n");

            UartPrint("converted_obj->TestString = %s\n", converted_obj->TestString);
            UartPrint("converted_obj->TestInt = %d\n", converted_obj->TestInt);
        }           
    }
}

return 0;

} `

运行结果: The Json is: { "TestString": "OK", "TestInt": ld } Converted OK! converted_obj->TestString = OK converted_obj->TestInt = 123

DebGith commented 1 year ago

我期望的输出结果是: { "TestString": "OK", "TestInt": 123 } @armink 请教大佬

DebGith commented 1 year ago

@yuxuebao 您知道吗