5、JsonCpp簡單使用(1)

weixin_34219944發表於2011-11-08

1、反序列化Json物件示例

示例程式碼

View Code
#include <iostream>
#include <string>
#include "json/json.h"

int main(void)
{
std::string strValue = "{\"key1\":\"value1\",\"array\":[{\"key2\":\"value2\"},{\"key2\":\"value3\"},{\"key2\":\"value4\"}]}";
Json::Reader reader;
Json::Value value;

if (reader.parse(strValue, value))
{
std::string out = value["key1"].asString();
std::cout << out << std::endl;
const Json::Value arrayObj = value["array"];
for (int i = 0; i < arrayObj.size(); i++)
{
out = arrayObj[i]["key2"].asString();
std::cout << out;
}
}
return 0;
}

2、序列化物件

示例程式碼

View Code
#include <iostream>
#include <string>
#include "json/json.h"

int main(void)
{
Json::Value root;
Json::Value arrayObj;
Json::Value item;

for (int i = 0; i < 10; i ++)
{
item["key"] = i;
arrayObj.append(item);
}

root["key1"] = "value1";
root["key2"] = "value2";
root["array"] = arrayObj;
//root.toStyledString();
std::string out = root.toStyledString();
std::cout << out << std::endl;
return 0;
}

 

result
{
"array" : [
{
"key" : 0
},
{
"key" : 1
},
{
"key" : 2
},
{
"key" : 3
},
{
"key" : 4
},
{
"key" : 5
},
{
"key" : 6
},
{
"key" : 7
},
{
"key" : 8
},
{
"key" : 9
}
],
"key1" : "value1",
"key2" : "value2"
}

編譯:

g++ -o json_t json_t2.cpp -I/usr/include/json /usr/include/json/libjson.a son.a

3、示例3

另一種方法來遍歷資料

示例程式碼

View Code
#include <iostream>
#include <string>
#include "json/json.h"

using namespace std;
int main(void)
{
string strValue = "{\"key1\":\"value1\",\"array\":[{\"key2\":\"value2\",\"key3\":\"aa\"},{\"key2\":\"value3\",\"key3\":\"bb\"},{\"key2\":\"value4\",\"key3\":\"cc\"}]}";
Json::Reader reader;
Json::Value value;

//method1
if (reader.parse(strValue, value))
{
std::string out = value["key1"].asString();
std::string out2;
std::cout << out << std::endl;

const Json::Value arrayObj = value["array"];
for (int i = 0; i < arrayObj.size(); i++)
{
out = arrayObj[i]["key2"].asString();
out2 = arrayObj[i]["key3"].asString();
std::cout << out << " : " << out2 << endl;
}
}
cout << "----------------" << endl;

//另一種,用他內建的迭代器,其實也就是他自己的一個vector<string>成員,
//可以自己去看json:value的定義
Json::Value::Members member;//Members 就是vector<string>,typedef了而已
if (reader.parse(strValue, value))
{
std::string out = value["key1"].asString();
std::string out2;
std::cout << out << std::endl;

const Json::Value arrayObj = value["array"];
for (Json::Value::iterator itr = arrayObj.begin(); itr != arrayObj.end(); itr++)
{
member = (*itr).getMemberNames();
string out1, out2;
bool flag = true;
for (Json::Value::Members::iterator iter = member.begin(); iter != member.end(); iter++)
{
if (flag)
{
out1 = (*itr)[(*iter)].asString();
flag = false;
}
else
{
out2 = (*itr)[(*iter)].asString();
}
}
cout << out1 << " : " << out2 << endl;
}
}
return 0;
}

 

View Code
value1
value2 : aa
value3 : bb
value4 : cc
----------------
value1
value2 : aa
value3 : bb
value4 : cc

參考

1】 示例來源網址

http://www.cnblogs.com/logicbaby/archive/2011/07/03/2096794.html

相關文章