lzx1413's blog

JsonCpp 解析json小结

jsoncpp的github地址是jsoncpp,可以比较好的decode和encode Json数据结构,json是一种轻量数据表示类型,可以表示整数,实数,字符串和顺序序列,键值对等,下面是json的一个例子:

1
2
3
4
5
{
"encoding" : "UTF-8",
"plug-ins" :["Python","c++","ruby"],
"indent" :{"length" : 3,"use_space":true}
}

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Json::Value root; //will contains the root value after parsing.
Json::Reader reader;
bool parsingSuccessful = reader.parse(config_doc,root);
if(!parsingSuccessful)
{
//report to the user the failure and their location in the document
std::cout<<"Faliled to parse configuration\n"
<<reader.getFormattedErrorMessages();
return;
}
//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 memeber of rootn named 'encoding',return a 'null' value if there is no such member.
const Json::Value plugins = root["plug-ins"];
for(int index = 0;index<plugins.size();++index)
loadPlugIn(plugins[index].asString());
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"] = getCurrentEncoding();
root["indent"]["length"] = getCurrentIndentLength();
root["indent"]["use_space"] = getCurrentIndentUseSpace();
Json::StyledWriter writer;
//Make a new JSON document for the configuration, Preserve original comments.
std::string outputConfig = writer.write(root);
//You can also use a stream this will push 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;