¿Cómo obtener datos en JSON usando lenguaje C?
La forma de obtener datos en JSON en lenguaje C es utilizar CJSON.
La siguiente es una breve introducción a la idea y la implementación del uso de CJSON:
1) Cree json y obtenga datos de json.
#nclude lt;stdio.hgt;?
#include "cJSON.h"
char * makeJson()
{
cJSON * pJsonRoot = NULL;
pJsonRoot = cJSON_CreateObject()
if(NULL == pJsonRoot)
{ p>
//se produjo un error aquí
return NULL;
}
cJSON_AddStringToObject(pJsonRoot, "hello", "hello world");
cJSON_AddNumberToObject(pJsonRoot, "número", 10010);
cJSON_AddBoolToObject(pJsonRoot, "bool", 1);
cJSON * pSubJson = NULL; p>
p>
pSubJson = cJSON_CreateObject();
if(NULL == pSubJson)
{
// error al crear el objeto , salir
cJSON_Delete(pJsonRoot);
regresar NULL;
}
cJSON_AddStringToObject(pSubJson, "subjsonobj", "un sub json string");
cJSON_AddItemToObject(pJsonRoot, "subobj", pSubJson);
char * p = cJSON_Print(pJsonRoot);
// demás uso :?
// char * p = cJSON_PrintUnformatted(pJsonRoot);
if(NULL == p)
{
/ /convertir lista json a cadena falló, salir
//porque el sub json pSubJson se ha agregado a pJsonRoot, así que simplemente elimine pJsonRoot, si también elimina pSubJson, se realizará un volcado y el error es: doble libre
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 == pJso
n)?
{
// análisis fallido, retorno
retorno;
}
// obtener cadena de json
cJSON * pSub = cJSON_GetObjectItem(pJson, "hola");
if(NULL == pSub)
{
//obtener el objeto llamado "hola" falló
}
printf("obj_1: s\n", pSub-gt; valuestring);
// obtener número de json
pSub = cJSON_GetObjectItem(pJson, "número");
if(NULL == pSub)
{
//obtener número de json falld
}
printf("obj_2: d\n", pSub-gt; valueint);
// obtener bool de json
pSub = cJSON_GetObjectItem(pJson, "bool");
if(NULL == pSub)
{
// obtener bool de json fallido
}?
printf("obj_3: d\n", pSub-gt; valueint);
// obtener subobjeto
pSub = cJSON_GetObjectItem(pJson, "subobj");
if(NULL == pSub)
{
// falló la obtención del subobjeto
}
cJSON * pSubSub = cJSON_GetObjectItem(pSub, "subjsonobj");
if(NULL == pSubSub)
{
// obtener el objeto del objeto sujeto falló
}
printf("sub_obj_1: s\n", pSubSub- gt; cadena de valor);
cJSON_Delete(pJson);
}
int main()
{
char * p = makeJson();
if(NULL == p)
{
return 0;
}
printf("s\n", p);
parseJson(p);
free(p); //No olvides liberar el memoria aquí, función cJSON_Print () o la memoria generada por cJSON_PrintUnformatted(), use free(char *) para liberar
return
}
2; ) Cree una matriz json y analice la matriz json
// Cree una matriz. El valor de la matriz es otro elemento JSON que se utiliza aquí.
A modo de demostración
char * makeArray(int iSize)
{
cJSON * root = cJSON_CreateArray();?
if( NULL == raíz)
{
printf("crear matriz json fallida\n");
return NULL;
}
int i = 0;
for(i = 0; i lt; iSize; i )
{
cJSON_AddNumberToObject(raíz , "jeje", i);
}
char * out = cJSON_Print(raíz);
cJSON_Delete(raíz);
return out;
}
//Analiza la matriz CJSON ahora mismo
void parseArray(char * pJson)
{
if(NULL == pJson)
{?
return ;
}
cJSON * raíz = NULL;
if((root = cJSON_Parse(pJson)) == NULL)
{
return;
} p>
int iSize = cJSON_GetArraySize(raíz);
for(int iCnt = 0; iCnt lt; iSize; iCnt)
{
cJSON * pSub = cJSON_GetArrayItem(raíz, iCnt);
if(NULL == pSub)
{
continuar;
}
int iValue = pSub-gt; valueint;
printf("valor[2d] : [d]\n", iCnt, iValue); ?
cJSON_Delete(root);
return;
}
Hay dos métodos:?
Uno es El método estándar de entrada y salida, como crear un nuevo archivo de disco c:\a.txt y escribir una cadena ingresada desde el teclado en el archivo:?
FILE *ft;?
char str[50];?
ft=fopen("c:\\a.txt", "w");?
printf("Ingrese un cadena: ") ;?
scanf("s", str);?
fputs(str, ft);?
fclose(ft);
//Vuelva a abrir este archivo, lea la cadena y muéstrela en la pantalla ft=fopen("c:\\a.txt", "rt");?
fgets(str, 50, ft);?
fclose(ft); printf("s", str ?
En segundo lugar, el método de entrada y salida de bajo nivel es sigue siendo el mismo que el ejemplo anterior:?
int hd; char str[50];
p>
scanf("s",str);
hd=open("c:\\a.txt",O_CREAT|O_TEXT|O_WRONLY);
escribir (hd, str, strlen(str));?
close(hd); //Vuelva a abrir este archivo, lea la cadena y muéstrela en la pantalla.
hd=open("c:\\a.txt", O_TEXT|O_RDONLY); read(hd, str, 50);?
close(hd); "s", cadena).