JSON文件学习(jsoncjson-c)(不要学这个,去学cJSON)

Posted Dontla

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSON文件学习(jsoncjson-c)(不要学这个,去学cJSON)相关的知识,希望对你有一定的参考价值。

json-c从会使用到自实现

json-c和jsoncpp的api使用教程(附视频链接)

文章目录

json-c和jsoncpp的api使用教程(附视频链接)

1.json的介绍

  • JSON 指的是 javascript 对象表示法(JavaScript Object Notation 【JavaScript对象标记】)
  • JSON 是轻量级的文本数据交换格式
  • JSON 独立于语言:JSON 使用 Javascript语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。 目前非常多的动态(php,JSP,.NET)编程语言都支持JSON。
  • JSON 具有自我描述性,更易理解

2.json格式的实例

myObj = 
    "name":"mr_zhou",
    "num":3,
    "sites": [
         "name":"Google", "info":[ "android", "Google 搜索", "Google 翻译" ] ,
         "name":"Baidu", "info":[ "百度地图", "百度AI", "百度翻译" ] ,
         "name":"Taobao", "info":[ "淘宝", "网购" ] 
    ]

json套json,键不管,值用[]括起来

3.json-C的安装

Ubuntu操作系统

sudo apt-get install libjson0-dev libjson0

4.json-C的api介绍

创建一个引用计数为1的新空对象

struct json_object * object = json_object_new_object();

向类型为object的对象添加对象字段

int result = json_object_object_add(struct json_object *obj, const char *key, struct json_object *val);

将c字符串转换为json字符串格式的对象

struct json_object * obj = json_object_new_string(const char *s);

将整数转换为json格式的对象

struct json_object * obj = json_object_new_int(int32_t i);

将object对象转化为json格式的字符串

const char * str = json_object_to_json_string(struct json_object *obj);

将字符串解析成json对象

struct json_object * json = json_tokener_parse(const char *str);

根据键名获取对应的json对象

json_bool res = json_object_object_get_ex(const struct json_object *obj, const char *key, struct json_object **value);

获取json对象的整型值

int32_t res = json_object_get_int(const struct json_object *obj);

获取json对象的字符串值

const char * str = json_object_get_string(struct json_object *obj);

获取json对象类型

enum json_type type = json_object_get_type(const struct json_object *obj);

创建一个json数组类型JSON对象

struct json_object * array = json_object_new_array();

往json_type_array类型的json对象中添加一个元素

int res = json_object_array_add(struct json_object *obj, struct json_object *val);

获取json_type_array类型的对象中指定下标的元素

struct json_object * obj3 = json_object_array_get_idx(const struct json_object *obj, size_t idx);

5.使用json-C的例子

使用的json格式字符串是:"name":"mr_zhou","age":20,"score":["chinese":100,"chinese:"80,"chinese":90]

Github:json-c/json-c

https://github.com/json-c/json-c is the official code repository for json-c. 
See the wiki for release tarballs for download. API docs at http://json-c.github.io/json-c/
https://github.com/json-c/json-c是json-c的官方代码库。
请参见wiki以获取下载的发布tarballs。API文档位于http://json-c.github.io/json-c/

JSON-C - A JSON implementation in C

JSON-C implements a reference counting object model that allows you to easily construct JSON objects in C, output them as JSON formatted strings and parse JSON formatted strings back into the C representation of JSON objects. It aims to conform to RFC 7159.

JSON-C 实现了一个引用计数对象模型,使您可以轻松地在 C 中构造 JSON 对象,将它们输出为 JSON 格式的字符串,并将 JSON 格式的字符串解析回 JSON 对象的 C 表示形式。 它旨在符合 RFC 7159。

Skip down to Using json-c or check out the API docs, if you already have json-c installed and ready to use.

如果您已经安装了 json-c 并准备好使用,请跳至使用 json-c 或查看 API 文档。

Home page for json-c: https://github.com/json-c/json-c/wiki

Build Status:

  • AppVeyor Build
  • Travis Build

Test Status

  • Coveralls Coverage Status

Building on Unix with git, gcc and cmake

If you already have json-c installed, see Linking to libjson-c for how to build and link your program against it.

如果您已经安装了 json-c,请参阅链接到 libjson-c,了解如何构建和链接您的程序。

Prerequisites:

  • gcc, clang, or another C compiler

  • cmake>=2.8, >=3.16 recommended, cmake=>3.1 for tests

To generate docs you’ll also need:

  • doxygen>=1.8.13

If you are on a relatively modern system, you’ll likely be able to install the prerequisites using your OS’s packaging system.

Install using apt (e.g. Ubuntu 16.04.2 LTS)

sudo apt install git
sudo apt install cmake
sudo apt install doxygen  # optional
sudo apt install valgrind # optional

Build instructions:

json-c GitHub repo: https://github.com/json-c/json-c

$ git clone https://github.com/json-c/json-c.git
$ mkdir json-c-build
$ cd json-c-build
$ cmake ../json-c   # See CMake section below for custom arguments

Note: it’s also possible to put your build directory inside the json-c source directory, or even not use a separate build directory at all, but certain things might not work quite right (notably, make distcheck)

Then:

$ make
$ make test
$ make USE_VALGRIND=0 test   # optionally skip using valgrind
$ make install

Generating documentation with Doxygen:

The library documentation can be generated directly from the source code using Doxygen tool:

# in build directory
make doc
google-chrome doc/html/index.html

CMake Options

The json-c library is built with CMake, which can take a few options.

Pass these options as -D on CMake’s command-line.

# build a static library only
cmake -DBUILD_SHARED_LIBS=OFF ..

Building with partial threading support

Although json-c does not support fully multi-threaded access to object trees, it has some code to help make its use in threaded programs a bit safer. Currently, this is limited to using atomic operations for json_object_get() and json_object_put().

Since this may have a performance impact, of at least 3x slower according to https://stackoverflow.com/a/11609063, it is disabled by default. You may turn it on by adjusting your cmake command with: -DENABLE_THREADING=ON

Separately, the default hash function used for object field keys, lh_char_hash, uses a compare-and-swap operation to ensure the random seed is only generated once. Because this is a one-time operation, it is always compiled in when the compare-and-swap operation is available.

cmake-configure wrapper script

For those familiar with the old autoconf/autogen.sh/configure method, there is a cmake-configure wrapper script to ease the transition to cmake.

mkdir build
cd build
../cmake-configure --prefix=/some/install/path
make

cmake-configure can take a few options.

Testing:

By default, if valgrind is available running tests uses it. That can slow the tests down considerably, so to disable it use:

export USE_VALGRIND=0

To run tests a separate build directory is recommended:

mkdir build-test
cd build-test
# VALGRIND=1 causes -DVALGRIND=1 to be passed when compiling code
# which uses slightly slower, but valgrind-safe code.
VALGRIND=1 cmake ..
make

make test
# By default, if valgrind is available running tests uses it.
make USE_VALGRIND=0 test   # optionally skip using valgrind

If a test fails, check Testing/Temporary/LastTest.log, tests/testSubDir/$testname/$testname.vg.out, and other similar files. If there is insufficient output try:

VERBOSE=1 CTEST_OUTPUT_ON_FAILURE=1 make test

or

JSONC_TEST_TRACE=1 make test

and check the log files again.

Building on Unix and Windows with vcpkg

You can download and install JSON-C using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install json-c

The JSON-C port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Linking to libjson-c

If your system has pkgconfig, then you can just add this to your makefile:

CFLAGS += $(shell pkg-config --cflags json-c)
LDFLAGS += $(shell pkg-config --libs json-c)

Without pkgconfig, you might do something like this:

JSON_C_DIR=/path/to/json_c/install
CFLAGS += -I$(JSON_C_DIR)/include/json-c
# Or to use lines like: #include <json-c/json_object.h>
#CFLAGS += -I$(JSON_C_DIR)/include
LDFLAGS+= -L$(JSON_C_DIR)/lib -ljson-c

If your project uses cmake:

  • Add to your CMakeLists.txt file:
find_package(json-c CONFIG)
target_link_libraries($PROJECT_NAME PRIVATE json-c::json-c)
  • Then you might run in your project:
cd build
cmake -DCMAKE_PREFIX_PATH=/path/to/json_c/install/lib64/cmake ..

Using json-c

To use json-c you can either include json.h, or preferably, one of the following more specific header files:
要使用 json-c,您可以包含 json.h,或者最好包含以下更具体的头文件之一:

  • json_object.h - Core types and methods. 核心类型和方法。
  • json_tokener.h - Methods for parsing and serializing json-c object trees. 解析和序列化 json-c 对象树的方法。
  • json_pointer.h - JSON Pointer (RFC 6901) implementation for retrieving objects from a json-c object tree. 用于从 json-c 对象树中检索对象的 JSON 指针 (RFC 6901) 实现。
  • json_object_iterator.h - Methods for iterating over single json_object instances. (See also json_object_object_foreach() in json_object.h) 迭代单个 json_object 实例的方法。 (另见 json_object.h 中的 json_object_object_foreach())
  • json_visit.h - Methods for walking a tree of json-c objects. 遍历 json-c 对象树的方法。
  • json_util.h - Miscellaneous utility functions. 杂项效用函数。
    For a full list of headers see files.html

The primary type in json-c is json_object. It describes a reference counted tree of json objects which are created by either parsing text with a json_tokener (i.e. json_tokener_parse_ex()), or by creating (with json_object_new_object(), json_object_new_int(), etc…) and adding (with json_object_object_add(), json_object_array_add(), etc…) them individually. Typically, every object in the tree will have one reference, from its parent. When you are done with the tree of objects, you call json_object_put() on just the root object to free it, which recurses down through any child objects calling json_object_put() on each one of those in turn.

json-c 中的主要类型是 json_object。 它描述了一个 json 对象的引用计数树,这些对象是通过使用 json_tokener(即 json_tokener_parse_ex())解析文本或通过创建(使用 json_object_new_object()、json_object_new_int() 等)并添加(使用 json_object_object_add( ), json_object_array_add(), 等等…) 它们分别。 通常,树中的每个对象都有一个来自其父对象的引用。 完成对象树后,您只需在根对象上调用 json_object_put() 以释放它,这会通过依次在每个子对象上调用 json_object_put() 的任何子对象向下递归。

You can get a reference to a single child (json_object_object_get() or json_object_array_get_idx()) and use that object as long as its parent is valid.
If you need a child object to live longer than its parent, you can increment the child’s refcount (json_object_get()) to allow it to survive the parent being freed or it being removed from its parent (json_object_object_del() or json_object_array_del_idx())

您可以获得对单个子对象(json_object_object_get() 或 json_object_array_get_idx())的引用,并使用该对象,只要其父对象有效。
如果您需要一个子对象的寿命比其父对象长,您可以增加子对象的引用计数 (json_object_get()) 以允许它在父对象被释放或从其父对象中移除时存活下来(json_object_object_del() 或 json_object_array_del_idx())

When parsing text, the json_tokener object is independent from the json_object that it returns. It can be allocated (json_tokener_new()) used one or multiple times (json_tokener_parse_ex(), and freed (json_tokener_free()) while the json_object objects live on.

解析文本时,json_tokener 对象独立于它返回的 json_object。 它可以被分配 (json_tokener_new()) 使用一次或多次 (json_tokener_parse_ex(),并在 json_object 对象存在时释放 (json_tokener_free())。

A json_object tree can be serialized back into a string with json_object_to_json_string_ext(). The string that is returned is only valid until the next “to_json_string” call on that same object. Also, it is freed when the json_object is freed.

可以使用 json_object_to_json_string_ext() 将 json_object 树序列化回字符串。 返回的字符串仅在对同一对象进行下一次“to_json_string”调用之前有效。 此外,它会在 json_object 被释放时被释放。

以上是关于JSON文件学习(jsoncjson-c)(不要学这个,去学cJSON)的主要内容,如果未能解决你的问题,请参考以下文章

前端学习之CSS

python学习之 -- 数据序列化

python学习之函数进阶三

Python学习之JSON格式的序列化和反序列化

学习日记——私活级ThinkPHP实战速学视频课程

不要这样学习C语言,这是个坑!