close

C++ 與 JSON - 使用 jsoncpp

jsoncpp 和 utf-8 的測試

環境
windows 11 64bit
Visual Studio 2022

在我換電腦之前就是使用 jsoncpp 在讀取 json 檔的,換了新電腦,整個作業系統、編譯器、IDE也全部換新之後,jsoncpp 就都不能用了,想當然之前封裝好的程式碼也全都不能用了,雖然這本來就在我換電腦的預期事件內,但還是感覺有點崩潰。

網路上關於 jsoncpp 的文章都偏舊,編譯的方式也非常複雜,真的是花了很多時間,才找到比較簡單的方法。

1. 下載

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

解壓縮之後會看到這樣的資料夾。

001.jpg

2. 安裝 python

https://www.python.org/downloads/

002.jpg

安裝完後在命令提示字元輸入
py --version
如果有看到這樣的畫面,表示安裝成功
如果沒有的話,檢查一下環境變數的設定(檢查)

003.jpg

3. 產生 jsoncpp 的檔案
回到剛才解壓縮的資料夾
會看到有一個 amalgamate.py 的檔案

004.jpg

用記事本寫一個 compile.bat 檔案

005.jpg

執行之後會看到這樣的畫面,資料夾裡也會產生 dist 資料夾。將資料夾裡的 include 和 dist 放到別的地方去。

006.jpg

007.jpg

008.jpg

4. 簡單測試

用記事本製作一個 simple.json,這預設會是一個 utf-8 的檔案

009.jpg

在專案裡加入 dist 資料夾裡的檔案,然後在程式碼裡加入 include

010.jpg

main.cpp

#include "K:\jsoncpp\include\json\json.h"
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
	ifstream ifs;
	ifs.open("simple.json");

	Json::Reader reader;
	Json::Value data;

	if (!reader.parse(ifs, data, false))
	{
		cout << "reader.parse Error." << endl;
		return 0;
	}
	
	bool ok = data["ok"].asBool();
	float height = data["height"].asFloat();
	int width = data["width"].asInt();
	std::string strName = data["name"].asString();
	
	cout << "ok: " << ok << endl;
	cout << "height: " << height << endl;
	cout << "width: " << width << endl;
	cout << "name: " << strName << endl;

	system("pause");
	return 0;
}

執行結果

011.jpg

5. utf-8 字元測試

以前工作常遇到多國語言的部分,所以每次做檔案或字串處理,我都一定會用日文做 unicode 的測試。

用剛剛的 simple.json 改個日文字串直接存成 simple2.json。

012.jpg

顯示 utf-8 的部分,因為我以前有一個 utf-8 轉 unicode 的函式,所以就直接用再 print 出來。

main.cpp

#include "K:\jsoncpp\include\json\json.h"
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
	ifstream ifs;
	ifs.open("simple2.json");

	Json::Reader reader;
	Json::Value data;

	if (!reader.parse(ifs, data, false))
	{
		cout << "reader.parse Error." << endl;
		return 0;
	}

	bool ok = data["ok"].asBool();
	float height = data["height"].asFloat();
	int width = data["width"].asInt();

	cout << "ok: " << ok << endl;
	cout << "height: " << height << endl;
	cout << "width: " << width << endl;

	//對 name 的 utf-8 做處理
	//轉成 unicode 後輸出
	string strName = data["name"].asString();
	wstring strUniName = hkstr::UTF8ToUnicode(strName);
	hkstr::PrintfUnicode(L"name: %s\n", strUniName.c_str());

	system("pause");
	return 0;
}

執行結果

013.jpg

 

參考資料
https://github.com/open-source-parsers/jsoncpp
https://www.youtube.com/watch?v=GYauneigGTs
https://www.cnblogs.com/zhangdongsheng/p/12731021.html
https://blog.csdn.net/zlyadvocate/article/details/122727602

arrow
arrow
    文章標籤
    C++ JSON jsoncpp
    全站熱搜

    kamory 發表在 痞客邦 留言(0) 人氣()