json-c从会使用到自实现

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

文章目录

  • json-c和jsoncpp的api使用教程(附视频链接)
    • 1.json的介绍
    • 2.json格式的实例
    • 3.json-C的安装
    • 4.json-C的api介绍
      • 创建一个引用计数为1的新空对象
      • 向类型为object的对象添加对象字段
      • 将c字符串转换为json字符串格式的对象
      • 将整数转换为json格式的对象
      • 将object对象转化为json格式的字符串
      • 将字符串解析成json对象
      • 根据键名获取对应的json对象
      • 获取json对象的整型值
      • 获取json对象的字符串值
      • 获取json对象类型
      • 创建一个json数组类型JSON对象
      • 往json_type_array类型的json对象中添加一个元素
      • 获取json_type_array类型的对象中指定下标的元素
    • 5.使用json-C的例子
  • Github:json-c/json-c
    • JSON-C - A JSON implementation in C
    • Building on Unix with git, gcc and cmake
      • Prerequisites:
      • Install using apt (e.g. Ubuntu 16.04.2 LTS)
      • Build instructions:
      • Generating documentation with Doxygen:
    • CMake Options
      • Building with partial threading support
      • cmake-configure wrapper script
    • Testing:
    • Building on Unix and Windows with vcpkg
    • Linking to libjson-c
    • Using json-c

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格式的实例

中括号{}代表一个JSON对象,JSON对象里能包含多个键值对,用,分隔,键值对中的值中能为各种类型,包括数组(里面能存相同类型的多个元素,包括{}JSON对象),和{}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 ..
makemake 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文件学习(jsonc、json-c)(不要学这个,去学cJSON)相关推荐

  1. python修改json文件_python修改json文件的value实例方法

    利用python修改json文件的value方法 做工程时遇到需要监听json文件,根据json文件中的key-value值作出相应处理的情形.为此写了修改json文件的python脚本供工程后续调用 ...

  2. python处理json文件_python处理json文件

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! python类型转换json类型的对应关系? json类型转换到python的类 ...

  3. [ app.json 文件内容错误] app.json: window.navigationBarTextStyle 字段需为 black,white【已解决】

    文章目录 异常信息 解决 异常信息 [ app.json 文件内容错误] app.json: window.navigationBarTextStyle 字段需为 black,white(env: W ...

  4. Python读取json文件及写入json文件等操作

    Python读取json文件及写入json文件等操作 读取json文件 写入json文件 读取json文件 load():用于读取json文件 import json with open(path,' ...

  5. 【JSON文件解析】JSON文件

    文章目录 概要:本期主要介绍Qt解析JSON数据格式文件的方式. 一.JSON数据格式 1.JSON类似于XML,在JSON文件中,==有且只有一个根节点 2.JSON有两种主流包含型构造字符:{对象 ...

  6. java读取json文件_Java 读取Json文件内容

    读取json文件为String类型: import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logge ...

  7. 解决微信小程序报[ app.json 文件内容错误] app.json: app.json 未找到,未找到入口 app.json 文件,或者文件读取失败,请检查后重新编译。小程序app.json报错

    编译报错:[ app.json 文件内容错误] app.json: app.json 未找到 原因:由于project.config.json文件的miniprogramRoot小程序根目录属性找不到 ...

  8. 解决微信小程序报[ app.json 文件内容错误] app.json app.json 未找到,未找到入口 app.json 文件,或者文件读取失败,请检查后重新编译。小程序app.json报错

    编译报错:[ app.json 文件内容错误] app.json: app.json 未找到 原因:由于project.config.json文件的miniprogramRoot小程序根目录属性找不到 ...

  9. 2014新生暑假个人排位赛01 B. 学姐去学车

    B. 学姐去学车 时间限制 1000 ms内存限制 65536 KB 题目描述 趁着放假,学姐去学车好带学弟去兜风.但是学车真的很辛苦,每天五点半就要起床赶班车,但是学姐的教练更辛苦,他们要相同的时间 ...

最新文章

  1. jQuery中的Ajax----03
  2. 基于K-gram的winnowing特征提取剽窃查重检测技术(概念篇)
  3. sigprocmask理解
  4. 思科服务器与交换机链接配置文件,使用思科S系列交换机上的配置迁移工具转换配置文件...
  5. [国家集训队]middle(二分+主席树[中位数思维题])
  6. 李群与李代数2:李代数求导和李群扰动模型
  7. curry化 js_前端发动机从 bind 聊到 curry (柯里化)
  8. EasyPOI之导出Excel复杂模板
  9. B帧对视频清晰度/码率的影响
  10. Ubuntu(debian) 程序 dep 打包
  11. yes we can
  12. TCP\IP 数据流与数据包
  13. linux,windows 可执行文件(ELF、PE)
  14. excel中如何实现在年龄一栏加1即让某列数字分别加1
  15. 第四章:用Python对用户的评论数据进行情感倾向分析
  16. 【正点原子MP157连载】第二十四章 设备树下的LED驱动实验-摘自【正点原子】STM32MP1嵌入式Linux驱动开发指南V1.7
  17. 智慧校园管理系统开发
  18. 【3d游戏开发】使用Babylonjs+Vue3搭建属于我们的小岛
  19. 快速扫描局域网主机的方式
  20. 数字电压电流表VCB

热门文章

  1. Linux下配置FTP、SSH服务
  2. byte转换int时为何与0xff进行与运算
  3. DevExpress.XtraBars.Ribbon控件使用系列 (1)创建Ribbon窗体
  4. 计算机信息处理技术知识点,计算机信息处理技术基础知识.doc
  5. linux qt 5移植,Qt 5.13支持处理Lottie文件,可以方便地进行移植
  6. java的(PO,VO,TO,BO,DAO,POJO)解释
  7. SAP固定资产的几个关键日期
  8. 特性,物料特性,批次特性(转自SAPNow)
  9. 小米+尚美的下沉CP,为酒店业释放了什么信号?
  10. 国产奶粉冲击高端,飞鹤、蒙牛、合生元们的牌好不好打?