现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

在c++中使用json:保存到文件、从文件中解析

2014-03-23 06:54 工业·编程 ⁄ 共 2227字 ⁄ 字号 暂无评论
文章目录

今天打算在服务器中加上一个xml表示当前服务器存在的video文件的列表的,大体上和数据库表中的值是一样的:

然后每次上传文件之后,都会生成一张这样的xml表,然后手机上边通过得到这种表,来获取目前服务器上边存在的视频文件

一开始打算用xml的

一开始打算用xml的,但是发现json比这更小(不过后来,作者打算两个方式都使用,xml还有很多的秘密……)

使用了一下jsoncpp,感觉还不错,像自己一直使用的库-----varint,不过方式不一样,varint使用的是map嵌套map得到索引的方式,当然也能够保存文件中,大体的操作方式和json惊奇的类似。

所以亲切感随之而来。

下面开始使用jsoncpp

首先是从http://sourceforge.net/projects/jsoncpp/下载到源代码,\jsoncpp-src-0.5.0\makefiles\vs71直接用vs编译,得到lib,贴个测试代码:

// test_json.cpp : 定义控制台应用程序的入口点。 
// 
 
#include "stdafx.h" 
#include "iostream" 
using namespace std; 
#include "string" 
#include "json/json.h" 
#pragma comment(lib, "json_vc71_libmtd.lib") 
#include "fstream" 
#include "assert.h" 
 
int ReadFromFile(string fileName) 

    ifstream fin; 
    fin.open(fileName); 
    assert(fin.is_open()); 
 
    Json::Reader reader; 
    Json::Value  root; 
    if (!reader.parse(fin, root, false)) 
    { 
        return -1; 
    } 
 
    // 获取数组中的数据 
    cout << "array data:" << endl; 
    int arraySize = root["array"]["map"].size(); 
    for (int i = 0; i <arraySize; i++) 
    { 
        Json::Value valKeyValue = root["array"]["map"][i]["arrayMap"]; 
        string tempKeyValue = valKeyValue.asString(); 
        cout << "array map arrayMap:" << tempKeyValue << endl; 
    } 
    cout << endl; 
 
    cout << "my age is:" << root["array"]["age"] << endl; 
 
    int arraySize2 = root["array"]["array1"].size(); 
    for (int i = 0; i <arraySize2; i++) 
    { 
        Json::Value valKeyValue = root["array"]["array1"][i]["key"]; 
        int tempKeyValue = valKeyValue.asInt(); 
        cout << "tempKeyValue:" << tempKeyValue << endl; 
    } 

 
int WriteToFile(string fileName) 

    ofstream fout; 
    fout.open(fileName); 
    assert(fout.is_open()); 
 
    Json::Value root; 
    Json::Value arrayObj; 
    Json::Value item; 
    Json::Value arrayMap; 
 
    for (int i = 0; i < 10; i++) 
    { 
        item["arrayMap"] = "zengraoli"; 
        arrayMap.append(item); 
    } 
    root["array"]["map"]= arrayMap; 
    root["array"]["age"] = 18; 
 
    Json::Value item2; 
    for (int i = 0; i < 10; i++) 
    { 
        item2["key"] = i; 
        arrayObj.append(item2); 
    } 
    root["array"]["array1"] = arrayObj; 
 
    std::string out = root.toStyledString(); 
 
    fout << root.toStyledString() << endl; 
    return 0; 

 
int _tmain(int argc, _TCHAR* argv[]) 

    WriteToFile("video.json"); 
 
    ReadFromFile("video.json"); 
 
    return 0; 

其实很简单
比如你想要

{

“zeng”{

"age" : 18

}

}

只需要root[“zeng”]["age"] = 18

数组比较难处理一些,可以参见上面的例子。

给我留言

留言无头像?