Install:
- libtool, autoconf, automake, doxygen
- sudo apt-get install libtool
- sudo apt-get install autoconf
Build:
- git clone https://github.com/json-c/json-c.git
- cd json-c
- ./autogen.sh
- ./configure
- make
- make install
- make check
- 在 /usr/local/lib/ 會看到 libjson-c.so.4.0.0 以及連結檔
Use - parser: (比較常用的)
- json_object_object_foreach
- json_object_get_type
- json_tokener_parse
- json_object_get_string
- json_object_object_get_ex
- json_object_object_get (gcc:不建議使用)
- json_object_put //free
example
Compiler:
- LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
- export LD_LIBRARY_PATH
- gcc xx.c -o xx -ljson-c
#include <json-c/json.h> #include <stdio.h> #include <unistd.h> #include <mcheck.h> int main() { //check memory leek setenv("MALLOC_TRACE", "output_file_name", 1); mtrace(); struct json_object *Object = json_object_new_object(); struct json_object *CpObject = json_object_new_object(); struct json_object *CpArray = json_object_new_array(); json_object_object_add(Object, "Time", json_object_new_string("yyyy_mm_dd")); json_object_object_add(Object, "Name", json_object_new_string("123")); json_object_object_add(Object, "Action", json_object_new_string("456")); json_object_object_add(CpObject, "Code", json_object_new_string("11")); json_object_object_add(CpObject, "Type", json_object_new_string("22")); json_object_object_add(CpObject, "SubType", json_object_new_string("33")); json_object_array_add(CpArray, CpObject); json_object_object_add(Object, "CpCommands", CpArray); printf ("%s\n",json_object_to_json_string(Object)); //free memory json_object_put(Object); json_object_put(CpObject); }example:
text.txt
{ "district" : "hello" }
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <mcheck.h>
#include <json-c/json.h>
#define READ_FILE_BUF 256
#define ONE_LOAD 16
#define READ_FILE_PATH "test.txt"
int test(char *dist)
{
FILE *fp=NULL;
char buf[READ_FILE_BUF]={0};
char str[ONE_LOAD];
char *tname="district"; //target_name
const char *gstr=NULL; //get string
if ((fp = fopen (READ_FILE_PATH, "r")) == NULL)
{
fprintf(stderr, "Can't open file\n");
}
while(!feof(fp) && !ferror(fp))
{
if(strlen(buf)>READ_FILE_BUF-ONE_LOAD)
{
fprintf(stdout,"buf oversize\n");
goto end;
}
if(fgets(str,16,fp)!=NULL)
{
str[strlen(str)-1]=0x20;
strncat(buf, str, ONE_LOAD);
fprintf(stdout, "buf=%s\n",buf);
}
}
json_object *jobj = json_tokener_parse(buf);
if(!jobj)
goto end;
json_object *val_obj = NULL;
if(json_object_object_get_ex(jobj, tname, &val_obj))
{
gstr = json_object_get_string(val_obj);
fprintf(stdout, "%s, %s: %s\n", __FUNCTION__, tname, gstr);
if(gstr==NULL)
{
fprintf(stderr, "Can't find target keyname in the file\n");
return 1;
}
else
{
strcpy(dist, gstr);
}
}
json_object_put(jobj);
fprintf(stdout, "dist=%s\n", dist);
fclose(fp);
return 0;
end:
json_object_put(jobj);
fclose(fp);
}
int main()
{
char dist[16];
test(dist);
return 0;
}
沒有留言:
張貼留言