C++解析JSON(jsonCpp)
JSON(java script Object Notation) 是一种轻量级的数据交换格式。它基于java script(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, java script, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(网络传输速度)
这里我们主要使用jsoncpp来解析json文件的
准备工作
下载jsoncpp">下载jsonCpp
我们首先新建一个文件夹jsonCpp,然后将jsoncpp克隆到我们的文件夹下面:
>mkdir jsonCpp && cd jsonCpp
>git clone https://github.com/open-source-parsers/jsoncpp.git
现在你的文件夹下面就会有一个jsoncpp文件夹,这里面就是jsoncpp的源码

编译jsoncpp
面对这个多个文件和文件夹,是不是有点混乱了,但是我们用到的东西就只有两个文件夹,一个是src/lib_json文件夹,一个是include/json文件夹

于是新建一个目录,并将这两个文件夹复制出来,将json文件夹复制到lib_json里面

下载我们就需要编译这些文件,并生成静态链接库,其实不编译也行,只是后面用起来方便一点,我们来编辑一个Makefile
TARGET=libjson.lib
SRCS=json_writer.cpp\
json_reader.cpp\
json_value.cpp
OBJS=$(SRCS:.cpp=.o)
INCS=-I json
$(TARGET):$(OBJS)
ar rv $@ $^
%.o:%.cpp
g++ -c $< $(INCS) -o $@
make 以后发现报错了
显示错误为:

报错找不到头文件
博主琢磨了一番,发现还是找不到解决方案(对makefile不太熟悉,有大神指点一下么?),只有改源文件了了,于是将json_value.cpp,json_reader.cpp,json_write.cpp这三个文件里面的头文件的尖括号改为双引号,然后make编译成功。

读取JSON文件
我们得到了jsonCpp的静态链接库libjson.lib,接下面我们开始用jsoncpp解析json文件了
从上面的编译可知,jsoncpp里面大致包含三个类:
Json::Value 用来保存读取的数据或者将要写入文件的数据 Json::Reader 用来读取JSON文件里面的数据,并传入到Json::Value对象里面去 Json::FastWriter 用来将Json::Value对象写入到一个JSON文件中去
读取简单的JSON文件
include
#include
#include "json/json.h" #include
using namespace std; int main() { ifstream inFile("test.json", ios::in); if(!inFile.is_open()) { cerr<<"Open the file failed"<
test.json里面的数据为:
{ "name":"qeesung", "age":21 }
我们编译一下:g++ main.cpp libjson.lib -o myJson
运行结果为:

读取含有数组的JSON文件
#include
#include
#include "json/json.h" #include
using namespace std; int main() { ifstream inFile("test.json", ios::in); if(!inFile.is_open()) { cerr<<"Open the file failed"<
json文件为:
[ {"name":"qeesung1","age":21}, {"name":"qeesung2","age":22}, {"name":"qeesung3","age":23}, {"name":"qeesung4","age":24} ]
编译运行结果为:

<??http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxoMiBpZD0="写入数据到son文件中">写入数据到SON文件中
#include
#include
#include "json/json.h" #include
using namespace std; int main() { ofstream outFile("test.json", ios::out | ios::trunc); if(!outFile.is_open()) { cerr<<"Open the file failed"<
我们得到结果:
[{"age":10,"root":"qeesung"},{"age":11,"root":"qeesung"},{"age":12,"root":"qeesung"}]