Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6319245
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类:

2012-12-09 09:49:32

原文:

So you want to parse JSON with C? Welcome aboard! First get json-c, configure, compile, and update your ld cache

Make JSON-C (libjson)

x86 / Ubuntu

wget

tar xf json-c-0.9.tar.gz

cd json-c-0.9

./configure && make && sudo make install

sudo ldconfig


ARM / OpenEmbedded

bitbake json-c


Simple Test

Now use one of the test files provided or this example:

json-example.c:


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stddef.h>
  4. #include <string.h>
  5. #include <json/json.h>

  6. int main(int argc, char **argv)
  7. {
  8.   struct json_object *new_obj;
  9.   int pageCount;
  10.   new_obj = json_tokener_parse("/* more difficult test case */ { \"glossary\": { \"title\": \"example glossary\", \"pageCount\": 100, \"GlossDiv\": { \"title\": \"S\", \"GlossList\": [ { \"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\", \"markup\"] } ] } } }");

  11.   printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  12.   new_obj = json_object_object_get(new_obj, "glossary");
  13.   printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  14.   new_obj = json_object_object_get(new_obj, "pageCount");
  15.   pageCount = json_object_get_int(new_obj);
  16.   printf("Page count = %d", pageCount);
  17.   json_object_put(new_obj);
  18.   return 0;
  19. }

Makefile:

all: static

# if you didn't do `sudo make install` you'll need to add your own paths

# to json.json.h and libjson.so - something like -I/usr/local/include/ -L/usr/local/lib

static:

  gcc -static -o json-example-static json-example.c -ljson

  ./json-example-static

shared:

  gcc -o json-example-shared json-example.c -L/usr/local/lib -ljson

  ./json-example-shared

.PHONY: all static shared


Make json-example

make static
make shared

Hopefully that's enough to get you started. The big thing is that when you compile your own projects, make sure that you include the json library and paths.

Segfaults
If you get a segfault it's most likely that you're accessing a key that doesn't exist.

阅读(1164) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~