Jsoncpp的安装配置及示例使用

Jsoncpp 安装

jsoncpp 是一个 c++封装的 json 包,跨平台支持 windowslinuxunix 等多系统。

linux 下面编译需要使用到 cmake 进行编译。

下载 jsoncpp 源码

git clone https://github.com/open-source-parsers/jsoncpp.git 

进到目录

cd jsoncpp-master

创建目录

mkdir -p build/release

进到编译目录

cd build/release

使用 cmake 进行编译

cmake -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -
DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_INCLUDEDIR=include/jsoncpp -
DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../..

编译和安装

make
sudo make install

 

文件引用

#include <json/json.h>

 

示例1 简单的构造一个json

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>


int main()
{
    std::cout << "Hello World!" << std::endl;

    Json::Value root;
    Json::FastWriter fast;

    root["ModuleType"] = Json::Value(1);
    root["ModuleCode"] = Json::Value("China");

    std::cout<<fast.write(root)<<std::endl;

    Json::Value sub;
    sub["version"] = Json::Value("1.0");
    sub["city"] = Json::Value(root);
    fast.write(sub);

    std::cout<<sub.toStyledString()<<std::endl;

    return 0;
}

 

示例2 加载解析

#include <string>
#include <jsoncpp/json/json.h>
#include <iostream>
 
using namespace std;
 
void readJson() {
	std::string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}";
 
	Json::Reader reader;
	Json::Value value;
 
	if (reader.parse(strValue, value))
	{
		std::string out = value["name"].asString();
		std::cout << out << std::endl;
		const Json::Value arrayObj = value["array"];
		for (unsigned int i = 0; i < arrayObj.size(); i++)
		{
			if (!arrayObj[i].isMember("cpp")) 
				continue;
			out = arrayObj[i]["cpp"].asString();
			std::cout << out;
			if (i != (arrayObj.size() - 1))
				std::cout << std::endl;
		}
	}
}

void writeJson() {
 
	Json::Value root;
	Json::Value arrayObj;
	Json::Value item;
 
	item["cpp"] = "jsoncpp";
	item["java"] = "jsoninjava";
	item["php"] = "support";
	arrayObj.append(item);
 
	root["name"] = "json";
	root["array"] = arrayObj;
 
	root.toStyledString();
	std::string out = root.toStyledString();
	std::cout << out << std::endl;
}

int main(int argc, char** argv) {
	readJson();
	writeJson();
	return 0;
}

 

 

jsoncpp的使用方法和性能

 

/*
 * @Descripttion: 测试jsoncpp的使用方法和性能
 * @version: 1.0
 * @Author: Milo
 * @Date: 2020-06-05 15:14:40
 * @LastEditors: Milo
 * @LastEditTime: 2020-06-05 15:14:40
 */
#include <memory>
#include <sstream>
#include <iostream>
#include <stdint.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/wait.h>
#include "jsoncpp/json/json.h"
#include "jsoncpp/json/value.h"
#include "jsoncpp/json/reader.h"
#include "jsoncpp/json/writer.h"

/*

{
  "name": "milo",
  "age": 80,
  "languages": ["C++", "C"],
  "phone": {
    "number": "186****3143",
    "type": "home"
  },
  "books":[
      {
          "name": "Linux kernel development",
          "price":7.7
      },
      {
          "name": "Linux server development",
          "price": 8.0
      }
  ],
  "vip":true,
  "address": null
}
 */

static uint64_t getNowTime()
{
    struct timeval tval;
    uint64_t nowTime;

    gettimeofday(&tval, NULL);

    nowTime = tval.tv_sec * 1000L + tval.tv_usec / 1000L;
    return nowTime;
}

std::string JsoncppEncodeNew()
{
    std::string jsonStr;
    // 一个value是可以包含多个键值对
    Json::Value root, languages, phone, book, books;

    // 姓名
    root["name"] = "milo";
    // 年龄
    root["age"] = 80;

    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;

    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;

    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = 7.7;
    books[0] = book;    // 深拷贝
    book["name"] = "Linux server development";
    book["price"] = 8.0;
    books[1] = book;    // 深拷贝
    root["books"] = books;

    // 是否为vip
    root["vip"] = true;

    // address信息空null
    root["address"] = "yageguoji";

    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;
    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(root, &os);
    jsonStr = os.str();

    // std::cout << "Json:\n" << jsonStr << std::endl;
    return jsonStr;
}

std::string JsoncppEncodeOld()
{
    std::string jsonStr;
    Json::Value root, languages, phone, book, books;

    // 姓名
     root["name"] = "milo";
    //root["name"] = Json::nullValue;
    // 年龄
    root["age"] =  80; 

    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;

    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;

    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = (float)7.7;
    books[0] = book;
    book["name"] = "Linux server development";
    book["price"] = (float)8.0;
    books[1] = book;
    root["books"] = books;

    // 是否为vip
    root["vip"] = true;

    // address信息空null
    root["address"] = "yageguoji"; //;// Json::nullValue; // 如果是null,则要用自定义的Json::nullValue,不能用NULL

    Json::FastWriter writer;
    jsonStr = writer.write(root);

    // std::cout << "Json:\n" << jsonStr << std::endl;
    return jsonStr;
}

// 不能返回引用
Json::Value JsoncppEncodeOldGet()
{
    Json::Value root;
    Json::Value languages, phone, book, books;

    // 姓名
    root["name"] = "milo";
    //root["name"] = Json::nullValue;
    // 年龄
    root["age"] =  80; 

    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;

    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;

    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = (float)7.7;
    books[0] = book;
    book["name"] = "Linux server development";
    book["price"] = (float)8.0;
    books[1] = book;
    root["books"] = books;

    // 是否为vip
    root["vip"] = true;

    // address信息空null
    root["address"] = Json::nullValue; //"yageguoji";// Json::nullValue; // 如果是null,则要用自定义的Json::nullValue,不能用NULL

 

    std::cout << "JsoncppEncodeOldGet:\n"  << std::endl;
    return root;
}

void printJsoncpp(Json::Value &root)
{
    if(root["name"].isNull())
    {
        std::cout << "name null\n";
    }
    std::cout << "name: " << root["name"].asString() << std::endl;
    std::cout << "age: " << root["age"].asInt() << std::endl;

    Json::Value &languages = root["languages"];
    std::cout << "languages: ";
    for (uint32_t i = 0; i < languages.size(); ++i)
    {
        if (i != 0)
        {
            std::cout << ", ";
        }
        std::cout << languages[i].asString();
    }
    std::cout << std::endl;

    Json::Value &phone = root["phone"];
    std::cout << "phone number: " << phone["number"].asString() << ", type: " << phone["type"].asString() << std::endl;

    Json::Value &books = root["books"];
    for (uint32_t i = 0; i < books.size(); ++i)
    {
        Json::Value &book = books[i];
        std::cout << "book name: " << book["name"].asString() << ", price: " << book["price"].asFloat() << std::endl;
    }
    std::cout << "vip: " << root["vip"].asBool() << std::endl;

    if (!root["address"].isNull())
    {
        std::cout << "address: " << root["address"].asString() << std::endl;
    }
    else
    {
        std::cout << "address is null" << std::endl;
    }
}

bool JsoncppDecodeNew(const std::string &info)
{
    if (info.empty())
        return false;

    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    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;
        return false;
    }
    // printJsoncpp(root);

    return true;
}

bool JsoncppDecodeOld(const std::string &strJson)
{
    if (strJson.empty())
        return false;

    bool res;

    Json::Value root;
    Json::Reader jsonReader;

    res = jsonReader.parse(strJson, root);
    if (!res)
    {
        std::cout << "jsonReader.parse err. " << std::endl;
        return false;
    }

    // printJsoncpp(root);

    return true;
}

const char *strCjson = "{                 \
	\"name\":	\"milo\",         \
	\"age\":	80,                 \
	\"languages\":	[\"C++\", \"C\"],\
	\"phone\":	{                       \
		\"number\":	\"186****3143\",    \
		\"type\":	\"home\"            \
	},                                  \
	\"books\":	[{                         \
			\"name\":	\"Linux kernel development\",   \
			\"price\":	7.700000        \
		}, {                            \
			\"name\":	\"Linux server development\",   \
			\"price\":	8               \
		}],                             \
	\"vip\":	true,                   \
	\"address\":	null                \
}                                      \
";
#define TEST_COUNT 100000
int main()
{
    std::string jsonStrNew;
    std::string jsonStrOld;

    jsonStrNew = JsoncppEncodeNew();
    // JsoncppEncodeNew size: 337
    std::cout << "JsoncppEncodeNew size: " << jsonStrNew.size() << std::endl;
    std::cout << "JsoncppEncodeNew string: " << jsonStrNew << std::endl;
    JsoncppDecodeNew(jsonStrNew);

    jsonStrOld = JsoncppEncodeOld();
    // JsoncppEncodeOld size: 248
    std::cout << "\n\nJsoncppEncodeOld size: " << jsonStrOld.size() << std::endl;
    std::cout << "JsoncppEncodeOld string: " << jsonStrOld << std::endl;
    JsoncppDecodeOld(jsonStrOld);

    Json::Value root = JsoncppEncodeOldGet();
    Json::FastWriter writer;
    std::cout << "writer:\n"  << std::endl;
    std::string jsonStr = writer.write(root);
    std::cout << "\n\njsonStr string: " << jsonStrOld << std::endl;
#if 1
    uint64_t startTime;
    uint64_t nowTime;
    
    startTime = getNowTime();
    std::cout << "jsoncpp encode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppEncodeNew();
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp encode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;

    startTime = getNowTime();
    std::cout << "\njsoncpp encode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppEncodeOld();
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp encode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;

    startTime = getNowTime();
    std::cout << "\njsoncpp decode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppDecodeNew(jsonStrNew);
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp decode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;

    startTime = getNowTime();
    std::cout << "\njsoncpp decode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppDecodeOld(jsonStrNew);
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp decode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
#endif

    return 0;
}
g++ jsoncpp_demo01.c -o demo01 -ljsoncpp -std=c++11
g++ jsoncpp_demo02.c -o demo02 -ljsoncpp -std=c++11
g++ jsoncpp_speed.cpp -o jsoncpp_speed -ljsoncpp -std=c++11

 

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值