网络数据交换的格式已经很多了,但我看了JSON后,我发现它简单易懂,对于一些小应用来讲比较实用,最重要的是他更简单易用,想想之前在做dvb与ca程序通信时自己用字符串来交换数据的方式就是为了简单,那时是自己写了解析代码,如果早用上JSON就省事很多了.
int main(int argc, char *argv[])
{
const char *s = "{"
"\"name\":\"mxy\","
"\"age\":\"30\","
"\"work\":\"engineer\","
"\"address\":"
"{"
"\"city\":\"xi\'an\","
"\"street\":\"efive\""
"},"
"\"family\":"
"["
"{"
"\"relationship\":\"wife\","
"\"name\":\"rui\""
"},"
"{"
"\"relationship\":\"son\","
"\"name\":\"rui\""
"}"
"]"
"}";
Json::Reader reader;
Json::Value root;
if (reader.parse(s, root))
{
std::cout << "Dump: " << std::endl;
std::cout << "name: " << root["name"];
std::cout << "age: " << root["age"];
std::cout << "work: " << root["work"];
Json::Value addr = root["address"];
std::cout << "address: " << std::endl;
std::cout << "\tcity: " << addr["city"];
std::cout << "\tstreet: " << addr["street"];
Json::Value family = root["family"];
if (!family.isNull())
{
std::cout << "family: " << std::endl;
for (int j = 0; j < family.size(); j++)
{
Json::Value it = family[j];
std::cout << "\trelationship: " << it["relationship"];
std::cout << "\tname: " << it["name"];
}
}
std::cout << std::endl;
Json::FastWriter writer1;
std::cout << "FastWriter dump: " << std::endl;
std::cout << writer1.write(root) << std::endl;
Json::StyledWriter writer2;
std::cout << "StyledWriter dump: " << std::endl;
std::cout << writer2.write(root) << std::endl;
}
return 0;
}
这里主要用了Json::Value, Json::Reader, Json::Writer我感觉对于一般应用来讲,熟悉这几个已经够了,只是看你怎么去灵活使用它们了.
阅读(1669) | 评论(0) | 转发(0) |