使用的 JSON 版本是:rapidjson-v1.1.0-13-g5268211,简单的 Jason 解析功能:Simple Reader,将 Jason 的字段解析成:Key 和 内容。
使用 VS2008 的对话框工程模板建立的新工程,将如下代码放一个 .cpp 文件中,然后增加到工程中,最后在窗体初始化中调用函数 TestPrittyWriter 就可以得到想要的结果。
如下代码:
// simplereaderCe.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "rapidjson/reader.h" // Additional Include Directories: ../include using namespace rapidjson; /* * 功能: 解析 JSON 字符串,后面附解析示例。 */ struct MyHandler { bool Null() { printf("Null()\r\n"); return true; } bool Bool(bool b) { printf("Bool(boolalpha: %d)\r\n",b); return true; } bool Int(int i) { printf("Int(i: %d)\r\n",i); return true; } bool Uint(unsigned u) { printf("Uint(u: %d)\r\n",u); return true; } bool Int64(int64_t i) { printf("Int64(i: %d)\r\n",i); return true; } bool Uint64(uint64_t u) { printf("Uint64(u: %d)\r\n",u); return true; } bool Double(double d) { printf("Double(d: %d)\r\n",d); return true; } bool RawNumber(const char *str, SizeType length, bool copy) { printf("Number(str: %s,length: %d,boolalpha: %d)\r\n",str,length,copy); return true; } bool String(const char *str, SizeType length, bool copy) { printf("String(str: %s,length: %d,boolalpha: %d)\r\n",str,length,copy); return true; } bool StartObject() { printf("StartObject()\r\n"); return true; } bool Key(const char *str, SizeType length, bool copy) { printf("Key(str: %s,length: %d,boolalpha: %d)\r\n",str,length,copy); return true; } bool EndObject(SizeType memberCount) { printf("EndObject(memberCount: %d)\r\n",memberCount); return true; } bool StartArray() { printf("StartArray()\r\n"); return true; } bool EndArray(SizeType elementCount) { printf("EndArray: %d)\r\n",elementCount); return true; } }; int _tmain(int argc, _TCHAR *argv[]) { const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; MyHandler handler; Reader reader; StringStream ss(json); reader.Parse(ss,handler); // reader.h RAPIDJSON_NAMESPACE.GenericReader.Parse -> ParseResult Parse(InputStream& is, Handler& handler) // Debug 模式在 Jason 的头文件中无法单步执行???断点可以起作用. return 0; } /* StartObject() Key(str: hello,length: 5,boolalpha: 1) String(str: world,length: 5,boolalpha: 1) Key(str: t,length: 1,boolalpha: 1) Bool(boolalpha: 1) Key(str: f,length: 1,boolalpha: 1) Bool(boolalpha: 0) Key(str: n,length: 1,boolalpha: 1) Null() Key(str: i,length: 1,boolalpha: 1) Uint(u: 123) Key(str: pi,length: 2,boolalpha: 1) Double(d: 776530087) Key(str: a,length: 1,boolalpha: 1) StartArray() Uint(u: 1) Uint(u: 2) Uint(u: 3) Uint(u: 4) EndArray: 4) EndObject(memberCount: 7) */