이쿠의 슬기로운 개발생활

함께 성장하기 위한 보안 개발자 EverNote 내용 공유

코딩/C and C++

C++에서 JSON 사용

이쿠우우 2020. 9. 13. 11:40
반응형

C++에서 JSON 사용

JSON 라이브러리 적합성과 성능을 평가한 링크

c++ 의 json 라이브러리 = JSONKIT, jsoncpp, rapidjson, zoolib, jvar 등등

대표적으로 많이 사용되는 jsoncpp, Rapid Json, nlohmann json이 있음.

참고 : https://github.com/miloyip/nativejson-benchmark

 

JSON 설명 글 이동

JSON


Jsoncpp 사용법

사용법 1

jsoncpp 를 library 로 만들지 않고 단일 source 와 header 로 만들어서 프로젝트에 포함

 

1. jsoncpp download

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

 

2. 다운받은 json 폴더의 amalgamate.py 파일 실행.

dist 폴더가 생성됨

 

3. dist 폴더 이동.

jsoncpp.cpp , json.h, json-forwards.h

파일을 프로젝트 빌드 시 같이 빌드하면 됨.

 

 

사용법 2

라이브러리 형태로 만들어서 사용

 

1. jsoncpp download

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

 

2. 다운받은 json 폴더의 CMakeLists.txt 를 실행해서 프로젝트를 만들어냄

 

[명령어] 

cmake CMakeLists.txt -B json_git -G "Visual Studio 15 2017 Win64"

참고 =  "Visual Studio 15 2017 Win64" 항목은 설치된 Visual studio 버전에 맞는것으로 입력

 

참고 Windows OS에서 cmake 명령 사용법

download 사이트 :  https://cmake.org/download/

install 버전으로 다운받아서 설치

완료 상태

 

3.  ~\jsoncpp-master\json_git 폴더로 이동하면 프로젝트가 생성되어있음

JSONCPP.sln 실행

 

4. 프로젝트 빌드

jsoncpp_lib 빌드.

~\jsoncpp-master\json_git\src\lib_json\Debug 폴더로 이동하면 

jsoncpp.lib 파일이 생성.

 

5. 프로젝트 적용

~\JSON_test\jsoncpp 파일\jsoncpp-master\include\json 경로에 있는

header 파일과 상위에서 만든 jsoncpp.lib 파일을

적용하고자 하는 프로젝트에 복사해서 사용.

 

jsoncpp 참고 예제 코드

#include <iostream>
#include <fstream>
#include "json/json.h"

#pragma comment(lib, "jsoncpp.lib")


using namespace std;

void jsonWrite() {
	ofstream json_file;
	json_file.open("d:\\JSON_DATA.json");

	Json::Value Computer;
	Computer["CPU"] = "I7";
	Computer["RAM"] = "16G";

	Json::Value Language;
	Language["C++"] = "Visual Studio";
	Language["Python"] = "IDLE";

	Computer["Program"] = Language;
	Computer["HDD"] = "2TB";

	Json::Value Cable;
	Cable.append("Power");
	Cable.append("Printer");
	Cable.append("Mouse");

	Computer["Computer"]["Cable"] = Cable;

	Json::Value number;
	number["Int"] = 123;
	number["Double"] = 456.012;
	number["Bool"] = true;

	Computer["Computer"]["Number"] = number;

	Json::StreamWriterBuilder builder;
	builder["commentStyle"] = "None";
	builder["indentation"] = "    ";  // Tab
	unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());

	// 알파벳 순으로 write 된다.
	writer->write(Computer, &cout);
	writer->write(Computer, &json_file);
	cout << endl;  // add lf and flush

	json_file.close();
}

void jsonRead() {
	ifstream json_dir("d:\\JSON_DATA.json");
	Json::CharReaderBuilder builder;
	builder["collectComments"] = false;
	Json::Value value;

	JSONCPP_STRING errs;
	bool ok = parseFromStream(builder, json_dir, &value, &errs);

	if (ok == true)
	{
		cout << "CPU: " << value["CPU"] << endl;
		cout << "Program Python: " << value["Program"]["Python"] << endl;
		cout << "Computer Cable: " << value["Computer"]["Cable"] << endl;
		cout << "Computer Cable[0]: " << value["Computer"]["Cable"][0] << endl;
		cout << endl;

		cout << "Computer Number Int(as int): " << value["Computer"]["Number"].get("Int", -1).asInt() << endl;
		// "Int" 값이 없으면 -1 반환.
		cout << "Computer Number Int(as int): " << value["Computer"]["Number"]["Int"].asInt() << endl;
		// "Int" 값이 없으면 0 반환.
		cout << "Computer Number Double(as double): " << value["Computer"]["Number"].get("Double", -1).asDouble() << endl;
		// "Double" 값이 없으면 -1 반환.
		cout << "Computer Number Double(as string): " << value["Computer"]["Number"].get("Double", "Empty").asString() << endl;
		// "Double" 값이 없으면 Empty 반환.
		cout << "Computer Number Bool(as bool): " << value["Computer"]["Number"].get("Bool", false).asBool() << endl;
		// "Bool" 값이 없으면 false 반환.
		cout << endl;

		cout << "Root size: " << value.size() << endl;
		cout << "Program size: " << value["Program"].size() << endl;
		cout << "Computer Cable size: " << value["Computer"]["Cable"].size() << endl;
		cout << endl;

		int size = value["Computer"]["Cable"].size();
		// size() 값을 for 문에서 그대로 비교하면 warning C4018가 발생 한다.
		for (int i = 0; i < size; i++)
			cout << "Computer Cable: " << value["Computer"]["Cable"][i] << endl;
		cout << endl;

		for (auto i : value["Computer"]["Cable"])
			cout << "Computer Cable: " << i << endl;
	}
	else
	{
		cout << "Parse failed." << endl;
	}

}

void main() {
	printf("Json 파일 쓰기\n");
	jsonWrite();
	printf("\n\nJson 파일 읽기\n");
	jsonRead();
}

 

 


 

Rapid Json 라이브러리

사용법

1. RapidJson download

download link = https://github.com/Tencent/rapidjson

 

2. ~\rapidjson-master\include\rapidjson 폴더를 복사해서 프로젝트에 붙여넣기 한다.

rapidjson 관련 헤더파일 폴더.

프로젝트에 아래와 같이 배치하고

#include "rapidjson/document.h" 로 불러오면 사용할 준비 완료


(nlohmann) Json Modern c++ 라이브러리

 

사용법

https://github.com/nlohmann/json

 

 

 

 


제 글을 복사할 시 출처를 명시해주세요.
글에 오타, 오류가 있다면 댓글로 알려주세요! 바로 수정하겠습니다!


 

 

 

 

반응형

'코딩 > C and C++' 카테고리의 다른 글

동적라이브러리 (DLL) 코딩 및 적용  (0) 2020.11.30
네임드 파이프 (Named-Pipe)  (0) 2020.10.04
JSON  (0) 2020.09.13
C++11 문법적 변경 사항  (0) 2020.09.13
C와 C++ 차이점  (1) 2020.09.13