C++ 处理JSON学习记录,今天整理了一下,把测试代码全文发上来。
JSONCPP 官方地址:http://jsoncpp.sourceforge.net/
// study_json.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <json/json.h>
#include <string>
#if defined(_MSC_VER) && _MSC_VER >= 1310
# pragma warning( disable: 4996 ) // disable deprecation warning
#endif
using namespace std;
//打印任意json数据(类似php的print_r函数) 2012-6-30 by Dewei
//用法:
//#include <json/json.h>
//#include <string>
//using namespace std;
//string jsontxt = "{\"key_array\":[\"array_string\",\"123456\"],\"key_bool\":true,\"key_number\":\"123456789\",\"key_object\":{\"firtName\":\"Dewei\",\"lastName\":\"Zhu\"},\"key_string\":\"字符串测试\"}";
//Json::Reader reader;
//Json::Value jsobject;
//reader.parse(jsontxt, jsobject);
//print_json(jsobject);
void print_json(Json::Value &jsobject)
{
if (jsobject.empty()|| (!jsobject.isArray() && !jsobject.isObject()))
return;
for (Json::Value::iterator iter = jsobject.begin(); iter != jsobject.end(); ++iter)
{
Json::Value current_key = iter.key();
int num_size = 0;
if (current_key.isInt())
num_size = jsobject[current_key.asInt()].size();
else if (current_key.isString())
num_size = jsobject[current_key.asString()].size();
if (num_size != 0) {
std::cout << "\r\n memberName:" << iter.memberName() << std::endl;
print_json(*iter);
}
else {
//std::cout << " key:" << current_key << " index:" << iter.index()<<" value:"<< *iter << std::endl;
std::cout << " key:" << current_key <<" value:"<< *iter << std::endl;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
//生成json字符串
Json::Value temp;
temp["firtName"] = "Dewei";
temp["lastName"] = "Zhu";
Json::Value root;
root["key_string"] = Json::Value("字符串测试");
root["key_number"] = Json::Value("123456789");
root["key_bool"] = Json::Value(true);
root["key_object"] = temp;
root["key_array"].append("array_string");
root["key_array"].append("123456");
//Json::ValueType type = root.type();
//将Json::Value 对象转换为字符串
Json::FastWriter fast_writer;
std::string jsontext = fast_writer.write(root);
std::cout << jsontext << std::endl;
//将字符串转换为 Json::Value 对象
std::string jsontxt = jsontext;
Json::Reader reader;
Json::Value jsobject;
reader.parse(jsontxt, jsobject);
print_json(jsobject);
//std::cout << jsobject["key_object"] << std::endl;
getchar();
return 0;
}