這裏是一個小例子您如何使用boost :: spirit :: qi來達到此目的。
請注意,Boost確實是第三方庫!
假設,您收到一個JSON文件,幷包含以下內容保存它在JSON-將example.txt:
{
"Result":"1",
"gs":"0",
"ga":"0",
"la":"0",
"lb":"0",
"lc":"0",
"ld":"0",
"ex":"0",
"gd":"0"
}
現在,假設你要接收的關鍵的所有項目:文件的方式。這就是你如何能做到這一點:
#include <vector>
#include <string>
#include <fstream>
#include <map>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
namespace qi = boost::spirit::qi;
template<typename Iterator>
struct jsonparser : qi::grammar<Iterator, std::map<std::string, int>()>
{
jsonparser() : jsonparser::base_type(query, "JSON-parser")
{
using qi::char_;
using qi::int_;
using qi::blank;
using qi::eol;
using qi::omit;
query = omit[-(char_('{') >> eol)] >> pair % (eol | (',' >> eol)) >> '}';
pair = key >> -(':' >> value);
key = omit[*blank] >> '"' >> char_("a-zA-Z_") >> *char_("a-zA-Z_0-9") >> '"';
value = '"' >> int_ >> '"';
};
qi::rule<Iterator, std::map<std::string, int>()> query;
qi::rule<Iterator, std::pair<std::string, int>()> pair;
qi::rule<Iterator, std::string()> key;
qi::rule<Iterator, int()> value;
};
void main(int argc, char** argv)
{
// Copy json-example.txt right in the std::string
std::string jsonstr
(
(
std::istreambuf_iterator<char>
(
*(std::auto_ptr<std::ifstream>(new std::ifstream("json-example.txt"))).get()
)
),
std::istreambuf_iterator<char>()
);
typedef std::string::iterator StrIterator;
StrIterator iter_beg = jsonstr.begin();
StrIterator iter_end = jsonstr.end();
jsonparser<StrIterator> grammar;
std::map<std::string,int> output;
// Parse the given json file
qi::parse(iter_beg, iter_end, grammatic, output);
// Output the result
std::for_each(output.begin(), output.end(),
[](const std::pair<std::string, int> &item) -> void
{
std::cout << item.first << ":" << item.second << std::endl;
});
}
輸出:
Result:1
gs:0
ga:0
la:0
lb:0
lc:0
ld:0
ex:0
gd:0
我要問的很明顯的:爲什麼在地球上不能使用已存在的JSON的實現方式之一? – 2012-04-24 04:55:50
你有什麼嘗試?如果你不想使用庫,你必須編寫代碼。所以繼續做吧。當你完全停留在實現特定的東西時,請在這裏提問。 – Mat 2012-04-24 04:57:17
感謝您的意見。 – sachin 2012-04-24 05:01:37