jsoncpp使用

C++ 在VS 中使用 JsonCpp 本文档详细介绍了如何在Visual Studio (VS) 中下载、编译和使用JsonCpp库,包括通过CMake生成VS项目,配置项目属性以链接JsonCpp库,并给出了一个读写JSON的示例代码,帮助开发者快速理解和使用JsonCpp处理JSON数据。 阅读详情

jsoncpp简介

jsoncp是一个操作json类型的c++库,可用于json串的解析与构造。其优点是语法简单,但是效率不如rapidjson。
源码下载链接:open-source-parsers/jsoncpp
Documention: JsonCpp documentation

安装与使用

其中最简单的方法是执行项目根目录中的python脚本,构建头文件和源文件。

  1. 在安装Python环境的控制台中进入jsoncpp项目根目录,

  2. 执行命令:

python amalgamate.py
3. 将生成的dist目录拷贝到自己的项目中,其中包源文件jsoncpp.cpp和头文件json.h、json-forwards.h。

使用时只需要包含<json/json.h>即可

使用jsoncpp解析json串

基本步骤:

  1. 调用Json::Reader的parse方法,解析json串到Json::Value中.
  2. 使用[]或者get获取对应key的value.
  3. 对value进行类型判断,然后使用jsoncpp提供的转化函数转换成对应的值(调用asString等函数).
    jsoncpp中的类型判断函数如下:
bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isInt64() const;
bool isUInt() const;
bool isUInt64() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;       
bool isArray() const;
bool isObject() const;

jsoncpp中的类型转化函数如下:

  const char* asCString() const; ///< Embedded zeroes could cause you trouble!
#if JSONCPP_USING_SECURE_MEMORY
  unsigned getCStringLength() const; // Allows you to understand the length of
                                     // the CString
#endif
  JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
  /** Get raw char* of string-value.
   *  \return false if !string. (Seg-fault if str or end are NULL.)
   */
  bool getString(char const** begin, char const** end) const;
#ifdef JSON_USE_CPPTL
  CppTL::ConstString asConstString() const;
#endif
  Int asInt() const;
  UInt asUInt() const;
#if defined(JSON_HAS_INT64)
  Int64 asInt64() const;
  UInt64 asUInt64() const;
#endif // if defined(JSON_HAS_INT64)
  LargestInt asLargestInt() const;
  LargestUInt asLargestUInt() const;
  float asFloat() const;
  double asDouble() const;
  bool asBool() const;

下面是具体的解析伪代码示例(注释行为使用的deprecated的Json::Read类):

void parseJsonString(string & str)
{
    //Json::Reader json_reader;
    Json::CharReaderBuilder builer;
    builder["collectComments"] = false;
    Json::Value json_value;
    std::string errs;
    const char * p_str = str.c_str();
    Json::CharReader* reader = builder.newCharReader();
    //if(!json_reader.parse(p_str, p_str + str.size(), json_value, false) || (!json_value.isObject()))
    if(!reader->parse(p_str, p_str + str.size(), &json_value, &errs) || (!json_value.isObject()))
    {
        cout << "parse " << str << "fail" << endl;
        delete reader;
        return ;
    }

    Json::Value var = json_value["key"];
    if(var.isNull())
    {
        ...
    }else if(var.isObject)
    {
    	 cout << "var is a object" << endl;
        //continue to parse the object 
        ...
    }else if(var.isString())
    {
        cout << var.asString() << endl;
    }else if(var.isInt()){
		 ...
    }
    ...
    
    delete reader;
}

如果输入的json内容位于文件的话,可以使用Json::CharReadBuilder来解析[需要将如下的std::cin替换成fstream变量]:

// Here, using a specialized Builder, we discard comments and
// record errors as we parse.
Json::CharReaderBuilder rbuilder;
rbuilder["collectComments"] = false;
std::string errs;
Json::Value root;
bool ok = Json::parseFromStream(rbuilder, std::cin, &root, &errs);

使用jsoncpp构造json串

构造示例代码如下:

void constructJsonString(string & str)
{
    Json::Value root;
    Json::FastWriter writer;
    Json::Value element;
    element["name"] = "wang";
    root["key"] = element;
    str = writer.write(root);
    cout << str << endl;
 
}

在新的版本中FastWriter类被声明为deprecated,推荐使用StreamWriterBuilder,示例代码如下:

 void constructJsonString1(string & str)
 {
     Json::Value root;
     Json::StreamWriterBuilder writerbuilder;
     Json::Value element;
     element["name"] = "wang";
     root["key"] = element;
     str = Json::writeString(writerbuilder, root);
     cout << str << endl;
 }
JSONCPP库使用总结 JSONCPP是一个C++库,用于在C++环境中读写JSON数据。它是开源的,可以轻松集成到各种C++项目中。JSONCPP提供了简单直观的API,可以用来序列化对象到JSON,或者从JSON反序列化出对象。JSONCPP是一个成熟、稳定且易于使用的库,适合于需要在C++中处理JSON数据的项目。通过这篇博文,希望对大家如何在项目中集成和使用JSONCPP有了基本的了解和帮助。 阅读详情

相关推荐

JsonCpp基本用法

JsonCpp库在MFC工程中的基本用法,VS2012下C++编译通过,可运行

jsoncpp使用小结

一、jsoncpp介绍 jsoncpp是一个开源C++库,提供对JSON字符串序列化/反序列化的功能。 开源地址:https://github.com/open-source-parsers/jsoncpp 文档地址:http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html 二、jsoncpp的使用 jsoncpp主要包含三种类型的C++类 - value、reader、writer...

深之JohnChen的专栏 5754

Jsoncpp动态库与静态库

这是一个已经编译成动态库(dll)和静态库(lib)的Jsoncpp,适用于Windows软件开发的C++开发者。适用于使用Visual Studio开发的人员,库文件编译没有按照C的格式,所以更适合做C++方向的场景使用

JsonCpp使用方法详解

JSON全称为JavaScript ObjectNotation,它是一种轻量级的数据交换格式,易于阅读、编写、解析。jsoncpp是c++解析JSON串常用的解析库之一。 jsoncpp中主要的类: Json::Value:可以表示所有支持的类型,如:int , double ,string , object, array等。其包含节点的类型判断(isNull,isBool,isInt,

小米的修行之路 2万+

schrodinger 薛定谔

链接: https://pan.baidu.com/s/1Duh4GsoytIklvZp7TdHpWg 密码: wmr1 Linux系统版 进入 Schrodinger_Suites_2021-2_Linux-x86_64 sudo ./INSTALL 中间按默认的来即可,也可以自己调整安装目录。安装目录一定要记住。 安装完,把patcher 拷贝到安装目录 sudo ./patcher 点击Patch即可。 启动程序,进入安装目录 ./maestro ...

周迪新的博客 1万+

保姆级避坑指南:用Docker在Ubuntu 22.04上部署Isaac Sim 5.1.0,搞定宇树G1仿真环境

本文提供了一份详细的保姆级避坑指南,帮助用户在Ubuntu 22.04上通过Docker部署Isaac Sim 5.1.0,并成功搭建宇树G1仿真环境。文章涵盖了环境准备、Docker与NVIDIA容器工具包的配置、Isaac Sim镜像的定制化拉取与配置,以及宇树G1仿真环境的实战调试,旨在帮助开发者高效解决部署过程中的常见问题。

weixin_33728268的博客 207

JsonCpp的基本用法

1、JsonCpp C++库,允许操作JSON值,包括与字符串串行化和序列化。它可在反序列化/序列化步骤中保留现有注释,使其成为存储用户输入文件的便捷方式。是一个第三方JSON解析库,可将源码编译成方便使用动态链接库、静态链接库或者静态导入库的。jsconcpp 进行 JSON 解析的源码文件分布在 include/json、src/lib_json 下。 JsonCpp(1.8.4版本):htt...

king_weng的博客 4万+

dify1.3.1应用服务与数据服务分离,附件及插件包迁移至minio,实现离线部署,保证插件正常运行

dify1.3.1应用服务与数据服务分离,附件及插件包迁移至minio,实现离线部署,保证插件正常运行

Time_1023的博客 1872

JsonCpp使用方法及示例

文章目录下载使用静态库/动态库使用源文件demo头文件创建保存读取修改main 下载 Github地址 本人编译好的库以及生产的源码 使用静态库/动态库 linux: mkdir build cd build cmake -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .. make windows: 下载cmake

凉_白开的博客 4万+

FOC无刷电机磁编码器机械角度与电角度自动对齐校准及电机极对数自动获取的方法

本文提出磁编码器机械角度与电角度自动对齐校准方法及电机极对数自动获取方案。通过通直流电流使转子定向,读取机械角度并计算电角度偏移量,实现精确对齐;同时利用低速旋转时检测反电动势过零点次数,结合机械角度变化量自动计算极对数。核心算法包括转子定向、偏移量计算、极对数推导等步骤,并提供了基于STM32的C语言实现代码。该方法适用于工业伺服、机器人等高精度控制场景,需注意负载安全、参数调整和误差处理。两种自动化流程可有效解决电机安装调试中的角度对齐和参数识别问题。

qq_29653575的博客 2482

虚拟机扩容——非LVM分区

虚拟机扩容——非LVM分区

ytraister的博客 3905

c++的jsoncpp使用

本文主要讲jsoncpp的基本使用方式和json的概念和jsoncpp的编译方式

m0_54069809的博客 1409

【EPS精品教程】EPS2016三维测图版安装教程(附EPS2016安装包下载地址)

EPS地理信息工作站是北京清华山维新技术开发有限公司历经十五年精心研发和打造,为满足“以地理信息服务为中心”的信息化测绘生产需求而推出的测绘生产活动多种业务模块集成化软件系统。主要功能有:(1)测绘与地理信息多业务模块集成管理;(2)多元多尺度多种类数据集成管理;(3)跨平台异构数据转换;(4)数据监理;(5)自动缩编与综合;(6)坐标转换与动态投影;(7)地理信息模板定制;(8)GIS地理信息描述与CAD图形表达一体化支持;(9)GIS数据库更新维护;(10)图形打印与地图出版。 一、安装过程 EP..

智慧空间实验室 2万+

【开源库 | jsoncpp】jsoncpp 的使用教程,附带读写json数据的例子源码

本文介绍了 jsoncpp 的一些基础使用,以及介绍怎样使用jsoncpp读写json数据,并给出了例子的代码,加深理解。

wkd_007的博客 2710

有限元之有限元空间的构造

主要介绍有限元的空间构造方法。

欢迎各位大佬光临“寒舍”!请多多指点,共同进步! 762

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

JsonCpp的用法

这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 欢迎使用Ma...

OO_SEN的博客 1852

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

《Jsoncpp库》

在现代 C++ 开发中,处理 JSON 数据已成为家常便饭 —— 无论是配置文件解析、网络数据交换还是跨语言通信,JSON 都扮演着重要角色。今天我们就来深入学习一款强大的 C++ JSON 处理库:JSONCpp,从安装到实战,带你轻松掌握 JSON 数据处理技巧。

fwfxhhx的博客 825

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

JSONCPP的简单使用

JSONCPP下载地址:http://sourceforge.net/projects/jsoncpp。 1、从字符串中解析JSON //从字符串中解析json void parse_json_from_string() { printf("exec [parse_json_from_string]\r\n"); std::string szJson = "{ \"weatherin...

HelloKandy's Blog 4194

JSONCPP 遍历所有值

很久没写点东东了, 也来一个! 这些天做通信, C++的, 用到了JSON. 于是使用JSONCPP. 为了处理省事, 需要取得KEY名, 各种查资料, 找到了. 自己写了一个输出Json所有KEY:VALUE的方法, 放出来方便大家参考!    #include "json.h" typedef Json::Writer JsonWriter; typedef Json::Reader J

ayktx的专栏 1万+

QT 使用jsoncpp

编译jsoncpp   编译前先安装好python,scons,解压jsoncpp到目录e:\jsconcpp,查看目录下的readme,有关于编译的说明的,根据说明做相应操作就可以。 打开Visual Studio 2005 Command Prompt 命令行,输入以下命令进行编译 scons platform =msvc80   编译完成后在子目录libs\msvc80就生成了j

han99yi的专栏 734

jsoncpp讲解,让你秒会jsoncpp

1.创建一个json对象使用 Json::Value 对象来创建 JSON 数据然后使用 Json::FastWriter 或 Json::StyledWriter 来生成字符串//构建json格式字符串,注意构建出来是倒序的2.如何将接收到的json格式字符串转化为json对象并且解析/*asString():返回字符串类型的数据。asInt():返回整数类型的数据。asBool():返回布尔值类型的数据。

zbz123456789_的博客 577

Jsoncpp的安装与使用

JsonCpp 是一个C++库,用于解析和生成JSON数据。它支持解析JSON文件或字符串到C++对象,以及将C++对象序列化回JSON格式。

2301_80926085的博客 3682

VS中使用JSONCPP:安装+使用

JSONCPP的下载安装和编译 下载地址:https://sourceforge.net/projects/jsoncpp/ JSONCPP的使用 案例一: #include <iostream> #include <string> #include "json.h" int main(void) { std::string strValue...

qq_40123329的博客 1139

JSONCPP使用

JSONCPP基础使用方法!

a12jggfdd的博客 1198

Jsoncpp使用简介

表示 JSON 数据中的各种值类型。:用于解析 JSON 字符串。和:用于将对象转换为 JSON 字符串。和:提供了更灵活的 JSON 解析选项。

2301_76606232的博客 1751
上一篇: rapidjson使用
下一篇: redis c编程
LinuxG_G
博客等级 码龄15年 58粉丝 176原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值