Build

  1. SourceForge 에서 0.6.0RC 다운로드
    1. wget http://sourceforge.net/projects/jsoncpp/files/jsoncpp/0.6.0-rc2/jsoncpp-src-0.6.0-rc2.tar.gz/download
  2. 압축 해제 및 폴더 이동
    1. tar zxvf jsoncpp-src-0.6.0-rc2.tar.gz
    2. cd jsoncpp-src-0.6.0-rc2
  3. scons 라는 python 으로 된 build 툴을 설치해야 한다.
    1. yum install scons -y
  4. platform 에 맞는 build 환경 구성 & compile

    scons platform=PLTFRM [TARGET]

    PLTFRM 은 환경에 맞게 기술하면 되고 다음과 같은 값이 설정 가능 (README.txt 참고)

    suncc Sun C++ (Solaris)
    vacpp Visual Age C++ (AIX)
    mingw
    msvc6 Microsoft Visual Studio 6 service pack 5-6
    msvc70 Microsoft Visual Studio 2002
    msvc71 Microsoft Visual Studio 2003
    msvc80 Microsoft Visual Studio 2005
    msvc90 Microsoft Visual Studio 2008
    linux-gcc Gnu C++ (linux, also reported to work for Mac OS X)

    사용하는 환경이 RHEL/CentOS 이므로 platform 에 linux-gcc 입력

    1. scons platform=linux-gcc
  5. test (check target 을 실행하면 됨)
    1. scons platform=linux-gcc check

 

Amalgamation

jsoncpp 를 library 로 만들지 않고 단일 source와 header 로 만들어서 프로젝트에 포함시킬수 있다.

  • python amalgamate.py

위 명령어를 실행하면 dist/ 폴더밑에 다음과 같은 세 개의 파일이 생성되며 이 파일을 프로젝트 빌드시 같이 빌드하면 된다.

  • jsoncpp.cpp
  • json
    • json.h
    • json-forwards.h

다음과 같은 에러가 발생할 경우 파일 경로가 / 가 아니라 \ 로 되어서 발생한 문제이다. amalgamate.py 를 열어서 add_file에 \ 로 된 파일을 찾아서 / 로 바꾸면 된다.

Traceback (most recent call last):
  File "amalgamate.py", line 147, in <module>
    main()
  File "amalgamate.py", line 139, in main
    header_include_path=options.header_include_path )
  File "amalgamate.py", line 111, in amalgamate_source
    source.add_file( 'src/lib_json\json_tool.h' )
  File "amalgamate.py", line 30, in add_file
    f = open( os.path.join( self.top_dir, relative_input_path ), 'rt' )
IOError: [Errno 2] No such file or directory: '/home/lesstif/work/jsoncpp-src-0.6.0-rc2/src/lib_json\\json_tool.h'
CODE

 

사용

http://garajeando.blogspot.kr/2011/06/we-are-using-json-javascript-object.html 에서 발췌한 예제

  1. 다음 소스를 test_json.cpp 로 저장

    test_json.cpp

    #include <cstdio>
    #include <cstring>
    // This is the JSON header
    #include "json/json.h"
    using namespace std;
    int main(int argc, char **argv)
    {
        string json_example = "{\"array\": \
                                [\"item1\", \
                                \"item2\"], \
                                \"not an array\": \
                                \"asdf\" \
                             }";
    	// Let's parse it
        Json::Value root;
        Json::Reader reader;
        bool parsedSuccess = reader.parse(json_example, root, false);
        if(not parsedSuccess)
        {
            // Report failures and their locations in the document.
            cout<<"Failed to parse JSON"<<endl
                <<reader.getFormatedErrorMessages()
                <<endl;
            return 1;
        }
    	// Let's extract the array contained in the root object
        const Json::Value array = root["array"];
    	// Iterate over sequence elements and print its values
        for(unsigned int index=0; index<array.size(); ++index)
        {
            cout<<"Element " <<index
                <<" in array: "
                <<array[index].asString()
                <<endl;
        }
    	// Lets extract the not array element contained in the root object and print its value
        const Json::Value notAnArray = root["not an array"];
        if(not notAnArray.isNull())
        {
            cout<<"Not an array: "
                <<notAnArray.asString()
                <<endl;
        }
    	// If we want to print JSON is as easy as doing:
        cout<<"Json Example pretty print: "
            <<endl<<root.toStyledString()
            <<endl;
        return 0;
    }
    CPP
  2. Amalgamation 된 세 개의 파일을 위 파일 경로에 복사((warning) header 는 json/ 폴더 밑에 위치)
  3. compile
    1. g++ -o test_json test_json.cpp jsoncpp.cpp -I. -DJSON_IS_AMALGAMATION
  4. 실행
    1. ./test_json

      Element 0 in array: item1
      Element 1 in array: item2
      Not an array: asdf
      Json Example pretty print:
      {
      "array" : [ "item1", "item2" ],
      "not an array" : "asdf"
      }

 

JsonCpp 사이트 예제
  1. example.json

    // Configuration options
    {
        // Default encoding for text
        "encoding" : "UTF-8",
        // Plug-ins loaded at start-up
        "plug-ins" : [
            "python",
            "c++",
            "ruby"
            ],
        // Tab indent size
        "indent" : { "length" : 3, "use_space": true }
    }     
    JS
  2. example.cpp

    example.cpp

    #include <stdlib.h>
    #include <fstream>
    // This is the JSON header
    #include "json/json.h"
    using namespace std;
    int main(int argc, char **argv)
    {
        ifstream ifs("example.json");
        Json::Value root;   // will contains the root value after parsing.
        Json::Reader reader;
        bool parsingSuccessful = reader.parse(ifs, root );
        if ( !parsingSuccessful )
        {
            // report to the user the failure and their locations in the document.
            std::cout  << "Failed to parse configuration\n"
                       << reader.getFormattedErrorMessages();
            return 0;
        }
    // Get the value of the member of root named 'encoding', return 'UTF-8' if there is no
    // such member.
        std::string encoding = root.get("encoding", "UTF-8" ).asString();
    // Get the value of the member of root named 'encoding', return a 'null' value if
    // there is no such member.
        const Json::Value plugins = root["plug-ins"];
        cout << "plug-ins : ";
        for ( int index = 0; index < plugins.size(); ++index )  // Iterates over the sequence elements.
            cout << plugins[index].asString() << ","; 
        cout << endl;
        //setIndentLength( root["indent"].get("length", 3).asInt() );
        //setIndentUseSpace( root["indent"].get("use_space", true).asBool() );
    // ...
    // At application shutdown to make the new configuration document:
    // Since Json::Value has implicit constructor for all value types, it is not
    // necessary to explicitly construct the Json::Value object:
        root["encoding"] = "UTF-16";
        root["indent"]["length"] = 5;
        root["indent"]["use_space"] = 0;
        Json::StyledWriter writer;
    // Make a new JSON document for the configuration. Preserve original comments.
        std::string outputConfig = writer.write( root );
    // You can also use streams.  This will put the contents of any JSON
    // stream at a particular sub-value, if you'd like.
        std::cin >> root["subtree"];
    // And you can write to a stream, using the StyledWriter automatically.
        std::cout << root;
        return 0;
    }
    CPP
  3. compile
    1. g++ -o example example.cpp jsoncpp.cpp -I. -DJSON_IS_AMALGAMATION
  4. 실행
    1. ./example
  5. jsonCPP 는 std::cin stream 에서 json 데이타를 입력받을수 있고 위 예제는 subtree 라는 value 를 요구하므로 아래와 같은 json data 를 입력하고 Ctrl-D 를 누르면 된다.

    ./example 
    plug-ins : python,c++,ruby,
    {    "name": "value",
        "arrary": {
            "age": 99,
            "ar": [
                1,
                2,
                3,
                4
            ]
        }
    }
    CODE

     

    결과

    {// Default encoding for text
    
            "encoding" : "UTF-16",// Tab indent size
    
            "indent" : 
            {
                    "length" : 5,
                    "use_space" : 0
            },// Plug-ins loaded at start-up
    
            "plug-ins" : [ "python", "c++", "ruby" ],
            "subtree" : 
            {
                    "arrary" : 
                    {
                            "age" : 99,
                            "ar" : [ 1, 2, 3, 4 ]
                    },
                    "name" : "value"
            }
    }
    CODE