用C语言获取JSON中的数据的方法是使用 CJSON。
以下简单介绍用CJSON的思路及实现:
1)创建json,从json中获取数据虚祥庆。
#nclude <stdio.h>
#include "cJSON.h"
char * makeJson()
{
cJSON * pJsonRoot = NULL
pJsonRoot = cJSON_CreateObject()
if(NULL == pJsonRoot)
{
//error happend here
return NULL
}
cJSON_AddStringToObject(pJsonRoot, "hello", "hello world")
cJSON_AddNumberToObject(pJsonRoot, "number", 10010)
cJSON_AddBoolToObject(pJsonRoot, "bool", 1)
cJSON * pSubJson = NULL
pSubJson = cJSON_CreateObject()
if(NULL == pSubJson)
{
// create object faild, exit
cJSON_Delete(pJsonRoot)
return NULL
}
cJSON_AddStringToObject(pSubJson, "subjsonobj", "a sub json string")
cJSON_AddItemToObject(pJsonRoot, "subobj", pSubJson)
char * p = cJSON_Print(pJsonRoot)
// else use :
// char * p = cJSON_PrintUnformatted(pJsonRoot)
if(NULL == p)
{
//convert json list to string faild, exit
//because sub json pSubJson han been add to pJsonRoot, so just delete pJsonRoot, if you also delete pSubJson, it will coredump, and error is : double free
cJSON_Delete(pJsonRoot)
return NULL
}
//free(p)
cJSON_Delete(pJsonRoot)
return p
}
void parseJson(char * pMsg)
{
if(NULL == pMsg)
{
return
}
cJSON * pJson = cJSON_Parse(pMsg);
if(NULL == pJson)
{
// parse faild, return
return
}
// get string from json
cJSON * pSub = cJSON_GetObjectItem(pJson, "hello")
if(NULL == pSub)
{
//get object named "hello" faild
}
printf("obj_1 : %s\n", pSub->宴纤valuestring)
// get number from json
pSub = cJSON_GetObjectItem(pJson, "number")
if(NULL == pSub)
{
//get number from json faild
}
printf("obj_2 : %d\n", pSub->valueint)
// get bool from json
pSub = cJSON_GetObjectItem(pJson, "bool")
if(NULL == pSub)
{
// get bool from json faild
}
printf("obj_3 : %d\n", pSub->valueint)
// get sub object
pSub = cJSON_GetObjectItem(pJson, "差握subobj")
if(NULL == pSub)
{
// get sub object faild
}
cJSON * pSubSub = cJSON_GetObjectItem(pSub, "subjsonobj")
if(NULL == pSubSub)
{
// get object from subject object faild
}
printf("sub_obj_1 : %s\n", pSubSub->valuestring)
cJSON_Delete(pJson)
}
int main()
{
char * p = makeJson()
if(NULL == p)
{
return 0
}
printf("%s\n", p)
parseJson(p)
free(p)//这里不要忘记释放内存,cJSON_Print()函数或者cJSON_PrintUnformatted()产生的内存,使用free(char *)进行释放
return 0
}
2)创建json数组和解析json数组
//创建数组,数组值是另一个JSON的item,这里使用数字作为演示
char * makeArray(int iSize)
{
cJSON * root = cJSON_CreateArray()
if(NULL == root)
{
printf("create json array faild\n")
return NULL
}
int i = 0
for(i = 0i <iSizei++)
{
cJSON_AddNumberToObject(root, "hehe", i)
}
char * out = cJSON_Print(root)
cJSON_Delete(root)
return out
}
//解析刚刚的CJSON数组
void parseArray(char * pJson)
{
if(NULL == pJson)
{
return
}
cJSON * root = NULL
if((root = cJSON_Parse(pJson)) == NULL)
{
return
}
int iSize = cJSON_GetArraySize(root)
for(int iCnt = 0iCnt <iSizeiCnt++)
{
cJSON * pSub = cJSON_GetArrayItem(root, iCnt)
if(NULL == pSub)
{
continue
}
int iValue = pSub->valueint
printf("value[%2d] : [%d]\n", iCnt, iValue)
}
cJSON_Delete(root)
return
}
有两种方法:
一是标准的输出输入方式 比如新建一个磁盘文件c:\a.txt, 将键盘输入的一字符串写到文件中:
FILE *ft
char str[50]
ft=fopen("c:\\a.txt","w+")
printf("输入一个字符串:")
scanf("%s",str)
fputs(str,ft)
fclose(ft)
//重新打开这个文件并读出字符串,显示在屏幕上 ft=fopen("c:\\a.txt","rt")
fgets(str,50,ft)
fclose(ft)printf("%s",str)
二是低级输入输出方式 仍如上例:
int hdchar str[50]printf("输入一个字符串:")
scanf("%s",str)
hd=open("c:\\a.txt",O_CREAT|O_TEXT|O_WRONLY)
write(hd,str,strlen(str))
close(hd)//重新打开这个文件并读出字符串,显示在屏幕上。
hd=open("c:\\a.txt",O_TEXT|O_RDONLY)read(hd,str,50)
close(hd)printf("%s",str)。
有的圆缺唯是 下面橘培是超市扮亮 请自选 JSON_checker. YAJL. js0n. LibU. json-c. json-parser. jsonsl. WJElement. M's JSON parser. cJSON. Jansson. jsmn. cson. parson. ujson4c. nxjson.1、读取文件全部内容#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char ch
FILE* fp
unsigned long int count = 0
char buf[1025] = {0}
// 这里要求我们在输入两个参数,第一个为 exe 路径,第二个为 文件名
// 如 file_test.exe test.txt
if (argc != 2)
{
printf("Usage: %s filename\n", argv[0])
exit(EXIT_FAILURE)
}
if ((fp = fopen(argv[1], "r")) == NULL)
{
// 如果文件打开失败(通常是文件不存在),则结束程序
printf("Can't open %s\n", argv[1])
exit(EXIT_FAILURE)
}
while ((ch = getc(fp)) != EOF &&count <1024)
{
// 显示文本内容并计数
buf[count] = ch
count++
}
fclose(fp)
printf("%s\n", buf)
printf("File %s has %lu characters\n", argv[1], count)
return 0
}
2、cJSON解析字符串
编译选项要加 -lm
示例源串
{
"server": {
"nodes": [{
"ip": "10.76.76.190",
"port": 6379
}, {
"ip": "丛哪10.76.76.191",
"port": 6380
}, {
"ip"冲郑卖: "10.76.76.192",
"port": 6381
}],
"password": "admin"
},
"isssl": true
}
登录后复制
示例代码(每一行记得判空,编译时加-lm选项)
#include <stdio.h>
#include "cJSON.h"
int main(){
char c[] = "{\"server\":{\"nodes\":[{\"ip\":\"10.76.76.190\",\"port\":6379},{\"ip\":\"10.76.76.191\",\"port\":6380},{\散逗"ip\":\"10.76.76.192\",\"port\":6381}],\"password\":\"admin\"},\"isssl\":true}"
cJSON* root = cJSON_Parse(c)
cJSON* json_server = cJSON_GetObjectItem(root, "server")
cJSON* json_isssl = cJSON_GetObjectItem(root, "isssl")
cJSON* json_password = cJSON_GetObjectItem(json_server, "password")
cJSON* json_nodes = cJSON_GetObjectItem(json_server, "nodes")
int i = 0
for (i != cJSON_GetArraySize(json_nodes)++i) {
cJSON* each = cJSON_GetArrayItem(json_nodes, i)
cJSON* json_ip = cJSON_GetObjectItem(each, "ip")
cJSON* json_port = cJSON_GetObjectItem(each, "port")
printf("ip %s\n", json_ip->valuestring)
printf("port %d\n", json_port->valueint)
}
printf("password %s\n", json_password->valuestring)
printf("is ssl %s\n", json_isssl->valueint ? "true":"false")
cJSON_Delete(root)
}
3、curl拿到回传的数据
编译选项要加 -lcurl
头部选项参考
https://curl.se/libcurl/c/curl_easy_setopt.html
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
struct string {
char* ptr
size_t len
}
void init_string(struct string* s) {
s->len = 0
s->ptr = malloc(s->len + 1)
if (s->ptr == NULL) {
fprintf(stderr, "malloc() failed\n")
exit(EXIT_FAILURE)
}
s->ptr[0] = '\0'
}
size_t writefunc(void* ptr, size_t size, size_t nmemb, struct string* s) {
size_t new_len = s->len + size * nmemb
s->ptr = realloc(s->ptr, new_len + 1)
if (s->ptr == NULL) {
fprintf(stderr, "realloc() failed\n")
exit(EXIT_FAILURE)
}
memcpy(s->ptr + s->len, ptr, size * nmemb)
s->ptr[new_len] = '\0'
s->len = new_len
return size * nmemb
}
int main(void) {
CURL* curl
CURLcode res
curl = curl_easy_init()
if(curl) {
struct string s
init_string(&s)
curl_easy_setopt(curl, CURLOPT_URL, "https://www.baidu.com")
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "test")
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc)
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s)
res = curl_easy_perform(curl)
printf("打印数据:\n%s", s.ptr)
free(s.ptr)
/* always cleanup */
curl_easy_cleanup(curl)
}
return 0
}
4、获取随机数
#include <stdio.h>
int main(int argc, char* argv[]){
srand((int)time(0))
//打印 32位 test 随机数,并用16进制表示
int test2 = rand()
printf("%lx \n", test2)
// 打印 64位 test 随机数,并用16进制表示, 016代表不足16位的部分,补零,llx代表打印64位的16进制数
unsigned long long test = ((unsigned long long)rand() <<32) + rand()
printf("%016llx \n", test)
return 0
}
5、定义按位的结构体
总结,按照位定义结构体,一定要都按照位定义,不然会出现意想不到的错误,而且一定要定义无符号的
#include <stdio.h>
#pragma pack (1)
struct test1 {
unsigned char cloud_id:3
unsigned char vendor_id:4
unsigned short machine_id
unsigned long long current_time:41
}
struct test2 {
unsigned char cloud_id:3
unsigned char vendor_id:4
unsigned short machine_id:16
unsigned long long current_time:41
}
int main(int argc, char* argv[]){
printf("test1 大小 : %d \n", sizeof(struct test1))
printf("test2 大小 : %d \n", sizeof(struct test2))
return 0
}
6、按位打印01字节码
#include <stdio.h>
// 修改type后面的类型,可以查看各种数的字节码
#define type unsigned int
void print_bin(type num)
{
int len = sizeof(type)
int n = 8
int i, j, k
unsigned char *p = (unsigned char*)&num + len -1
for (i = 0i <leni++) //处理len个字节
{
j = *(p - i)//取每个字节的首地址
for ( k = 7k >= 0k--) //处理每个字节的8个位
{
if (j &(1 <<k))
printf("1")
else
printf("0")
}
printf(" ")
}
printf("\r\n")
}
int main(int argc, char* argv[]){
type a = 100
print_bin(a)
return 0
}
登录后复制
7、打印16进制字节码
#include<stdio.h>
typedef unsigned char uint8
#define HEXDUMP_LINE_LENGTH 16
void hex_dump(uint8* data, int length)
{
uint8* p = data
int i, line, offset = 0
while (offset <length)
{
printf("%04x ", offset)
line = length - offset
if (line >HEXDUMP_LINE_LENGTH)
line = HEXDUMP_LINE_LENGTH
for (i = 0i <linei++)
printf("%02x ", p[i])
for (i <HEXDUMP_LINE_LENGTHi++)
printf(" ")
for (i = 0i <linei++)
printf("%c", (p[i] >= 0x20 &&p[i] <0x7F) ? p[i] : '.')
printf("\n")
offset += line
p += line
}
}
8、打印字节码简易版
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main() {
unsigned char Buf[] = "123456"
unsigned int len = strlen(Buf)
char* Buf1 = (char*)malloc(len * 3 + 1)
int i = 0, k = 0
for (i <len * 3i += 3, k++)
snprintf(&Buf1[i], 4, "%02x ", Buf[k])
printf(Buf1)
free(Buf1)
}
9、逐级创建文件夹
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
int mkdir_recursively(char* dir) {
if (NULL == dir)
return 1
size_t len = strlen(dir)
char* str = malloc(len + 1)
if (NULL == str)
return 1
strcpy(str, dir)
int i = 0
for (i = 0i <leni++) {
if (str[i] == '/') {
if (i == 0)
continue
str[i] = '\0'
if (access(str, 0) != 0) {
if (mkdir(str, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) {
free(str)
return 1
}
}
str[i] = '/'
}
}
if (len >0 &&access(str, 0) != 0) {
if (mkdir(str, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) {
free(str)
return 1
}
}
free(str)
return 0
}
int main() {
mkdir_recursively("/home/test/abc/edf")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)