天天看点

VS2008中使用JSONCPP方法小结

Introduction JSON (JavaScript Object Notation)  is a lightweight data-interchange format. It can represent integer, real number, string, an ordered sequence of value, and a collection of name/value pairs. For detail: http://www.json.org/index.html C++要使用JSON来解析数据,一般采用 jsoncpp

.

下载jsoncpp后,按ReadMe文档的说法是要先安装的,但是安装比较麻烦。然而事实上,我们并不需要安装,就可以直接使用。

方法一:直接拷贝源文件。这个方法比较简单,但不推荐,因为不便于项目管理。

  1. VS2008里新建一个空的控制台程序(用作测试jsoncpp是否可用),名为: TestJSON
  2. 解压下载好的文件:jsoncpp-src-0.5.0.tar.gz
  3. 将 jsoncpp-src-0.5.0\include 目录下的json文件夹拷贝至 TestJSON 工程目录下
  4. 将 jsoncpp-src-0.5.0\src\lib_json 目录下的所有.h, .cpp 文件全部拷贝至 TestJSON 工程目录下
  5. 在VS2008里引入工程目录下刚刚从 jsoncpp-src-0.5.0 导入的文件,如图1
  6. 在VS2008里新建main.cpp来测试jsoncpp是否可用。代码见文章末尾main.cpp

方法二:使用静态链接库

  1. 利用VS2008打开jsoncpp-src-0.5.0\makefiles\vs71目录下的jsoncpp.sln,会出现三个Project:jsontest, lib_json, test_lib_json
  2. 在lib_json上 右击-->Properties-->Configuration Properties-->C/C++-->Code Generation,注意右侧的Runtime Library的内容,如图2,看完箭头所指的东西就可以点确定,关掉属性页。
  3. 编译lib_json,显示编译成功后,在jsoncpp-src-0.5.0\build\vs71\debug\lib_json目录下会生成一个json_vc71_libmtd.lib,将这个lib拷贝至TestJSON工程目录下。
  4. 将jsoncpp-src-0.5.0\include\json目录下的所有.h文件拷贝至TestJSON工程目录下,并在工程Header Files引入.
  5. 将方法一里的main.cpp添加到工程中,并在工程名上 右击-->Properties-->Configuration Properties-->C/C++-->Code Generation, 将Runtime Library改成图2箭头所示内容。
  6. 在工程名上 右击-->Properties-->Configuration Properties-->Linker-->Input, 在Additional Dependencies里填写json_vc71_libmtd.lib,然后确定,编译就行了。

图1:

VS2008中使用JSONCPP方法小结

图2:

VS2008中使用JSONCPP方法小结
VS2008中使用JSONCPP方法小结
VS2008中使用JSONCPP方法小结
/* 测试jsoncpp的使用
 * [email protected]
 */

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

using namespace std;
using namespace Json;    //json的命名空间

int main()
{
    /*JSON DATA as following:            //一个json类型的数据    
    {
        "test : 5
    }*/

    string test = "{\"test\" : 5}";        //保存上文的json类型的数据

    //以下涉及json的操作,将在后文中涉及,此处为简单应用,不解释,你懂的
    Reader reader;
    Value value;

    if (reader.parse(test, value))
    {
        int i = 0;

        if (!value["test"].isNull())
        {
            i = value["test"].asInt();
            cout << i << endl;
        }
    }

    return 0;
}      
VS2008中使用JSONCPP方法小结

继续阅读