[C++, Json] jsoncpp 사용하기

2016. 1. 6. 18:34프로그래밍/C/C++

728x90
728x90

json 라이브러리 파일 다운로드

빌드하기

  • 압축을 푼 후 makefiles 폴더에서 sln 솔루션 열기.
  • jsoncpp 솔루션 Project Properties > C/C++ > Code Generation > Runtime Library에 /MDd로 설정. 물론 자신이 활용할 방식으로 설정하면 된다.
  • 컴파일 후 json_vc71_libmtd.lib 파일 가져오기.

테스트 프로젝트에 라이브러리 링크하기

  • 여러 방법이 있겠지만 라이브러리를 쓰기 위해선 2가지를 해야한다. 그것은 헤더 파일 링크, 라이브러리 링크 프로젝트 세팅에서 건드려도 되지만 나는 명시적으로 하는게 좋아서.. 프로젝트 내에 json폴더를 만들고 include 파일과 lib 파일을 모두 가져왔다.
#include "json/json.h"
#pragma comment(lib , "json/json_vc71_libmtd")

TEST

  • test.json에 원하는 형태로 json 덩어리가 만들어지고 바로 읽어들여 cmd에 출력하는 코드.
// test.cpp : Defines the entry point for the console application.
//

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

#pragma comment(lib , "json/json_vc71_libmtd.lib")

// write
bool WriteToFile(const char* filename, const char* buffer, int len)
{
    FILE* fp = nullptr;
    fopen_s(&fp ,filename, "wb");

    if (fp == nullptr)
    {
        return false;
    }

    size_t fileSize = fwrite(buffer, 1, len, fp);

    fclose(fp);

    return true;
}

// read
bool ReadFromFile(const char* filename, char* buffer, int len)
{
    FILE* fp = nullptr;
    fopen_s(&fp ,filename, "rb");

    if (fp == nullptr) 
    {
        return false;
    }

    size_t fileSize = fread(buffer, 1, len, fp);

    fclose(fp);

    return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
    // write test
    {
        Json::Value root;
        Json::Value encoding;
        root["encoding"] = "UTF-8";
        Json::Value plugins;
        plugins.append("python");
        plugins.append("c++");
        plugins.append("ruby");
        root["plug-ins"] = plugins;
        Json::Value indent;
        indent["length"] = 3;
        indent["use_space"] = true;
        root["indent"] = indent;
        Json::StyledWriter writer;
        std::string outputConfig = writer.write( root );
        bool result = WriteToFile("test.json", outputConfig.c_str(), outputConfig.length());
    }

    // read test
    {
        const int BufferLength = 1024;
        char readBuffer[BufferLength] = {0,};

        if (ReadFromFile("test.json", readBuffer, BufferLength) == false)
        {
            return -1;
        }

        std::string config_doc = readBuffer;
        Json::Value root;
        Json::Reader reader;
        bool parsingSuccessful = reader.parse( config_doc, root );

        if (parsingSuccessful == false)
        {
            std::cout  << "Failed to parse configuration\n" << reader.getFormatedErrorMessages();
            return -1;
        }

        std::string encoding = root.get("encoding", "").asString();
        std::cout << encoding << std::endl;
        const Json::Value plugins = root["plug-ins"];

        for ( unsigned int index = 0; index < plugins.size(); ++index )
        {
            std::cout << plugins[index].asString() << std::endl;
        }

        std::cout << root["indent"].get("length", 0).asInt() << std::endl;
        std::cout << root["indent"]["use_space"].asBool() << std::endl;
    }

    return 0;
}​

Updated

  • 20190517 라이브러리 경로 업데이트. 글 형태 markdown으로 변경.
728x90
반응형

'프로그래밍 > C/C++' 카테고리의 다른 글

[VS] tab, space 보기  (0) 2019.02.27
[Boost] 설치  (0) 2016.03.19
[C++] for each 써보기  (2) 2016.01.19
[C/C++] 삼항 연산자  (4) 2015.11.27
[C++11] 주요 기능들  (0) 2015.09.07
[C++/STL] STL 벡터와 배열 차이  (1) 2015.08.19
[C++] 스마트포인터(Smart Pointer)  (0) 2015.07.14