JSON 的全称为:JavaScript Object Notation,顾名思义,JSON 是用于标记 Javascript 对象的,JSON 官方的解释为:JSON 是一种轻量级的数据传输格式。
1、jsoncpp库下载
jsoncpp 是比较出名的 C++ JSON 解析库。在 JSON 官网也是首推的。
下载地址为:https://github.com/open-source-parsers/jsoncpp/tree/0.y.z
2、jsoncpp编译
windows平台:
打开makefiles/vs71/jsoncpp.sln 便可以开始编译
linux平台:
mkdir -p build/debug
cd build/debug
cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=OFF -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../..
make
3、jsoncpp 使用详解
在新的Jsoncpp中 Json::Writer
、Json::FastWriter
、Json::Reader
等都被摒弃了,用了新的Json::StreamWriterBuilder
、Json::CharReaderBuilder
代替。
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "json/json.h"
using namespace std;
bool parseJson(const std::string& info)
{
if (info.empty())
return false;
bool res;
JSONCPP_STRING errs;
Json::Value root, lang, mail;
Json::CharReaderBuilder readerBuilder;
std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
res = jsonReader->parse(info.c_str(), info.c_str() + info.length(), &root, &errs);
if (!res || !errs.empty()) {
std::cout << "parseJson err. " << errs << std::endl;
}
/******************* 打印JSON报文 *****************************************/
std::cout << "name: " << root["name"].asString() << std::endl;
std::cout << "Age: " << root["Age"].asInt() << std::endl;
//第一种数组输出方法
//std::cout << "addr: " << root["addr"] << std::endl; //全部输出
//第二种数组输出方法
lang = root["addr"];
for (int i = 0; i < lang.size(); ++i)
{
std::cout << lang[i] << " ";
}
std::cout << "key_array: " << root["key_array"]<< std::endl;
std::cout << std::endl;
return true;
}
int main()
{
/************* 生成JSON报文 *************************************/
std::string jsonStr;
const char* age;
Json::Value root;
Json::Value phone;
Json::StreamWriterBuilder writerBuilder;
std::ostringstream oss; //包含#include <sstream>
root["name"] = "mark";
root["age"] = 52;
phone["call"] = "xxxxxx";
phone["id"] = "11_xxxx";
root["addr"].append(phone); // 新建一个key为array,类型为数组,对第一个元素赋值为字符串“arr”
phone["call"] = "yyyyyy";
phone["id"] = "11_yyyyy";
root["addr"].append(phone); // 新建一个key为array,类型为数组,对第一个元素赋值为字符串“arr”
root["key_array"].append("array_string");// 新建一个 Key(名为:key_array),类型为数组,对第一个元素赋值为字符串:"array_string"。
root["key_array"].append(1234);
//第一种输出方法
// cout << root.toStyledString() << endl;
//第二种输出方法
//std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
//jsonWriter->write(root, &cout);
//第三种输出方法
std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
jsonWriter->write(root, &oss);
jsonStr = oss.str();
cout << jsonStr << endl; //格式化输出
/************* JSON报文解析 *************************************/
parseJson(jsonStr);
system("pause");
return 0;
}