使用示例
提供鲲鹏Json库函数接口完整使用示例。
- 创建test.cpp文件。
vi test.cpp
- 按“i”进入编辑模式,在文件中添加以下内容。
#include <iostream> #include "com_google_gson_JsonElement.h" #include "com_google_gson_JsonParser.h" #include "com_google_gson_Gson.h" #include "com_google_gson_GsonObject.h" int main() { std::string json_str = R"( { "intValue": 42, "longValue": 1726819335, "shortValue": 996, "doubleValue": 3.14, "floatValue": 0.00159, "stringValue": "Hello, World!", "stringValueFromInt64": 1726819335, "arrayValue": [1, 2, 3], "boolValue": true, "objectValue": { "nestedInt": 100, "nestedString": "Nested" }, "arrayObject": [ {"name": "hua", "age": 18}, {"name": "wei", "age": 20} ] } )"; String tmpStr(json_str); JsonElement *newElement = JsonParser::parseString(&tmpStr); GsonObject *gsonObject = newElement->getAsJsonObject(); int intValue = gsonObject->get("intValue")->getAsInt(); double doubleValue = gsonObject->get("doubleValue")->getAsDouble(); String *stringValue = gsonObject->get("stringValue")->getAsString(); std::cout << "intValue: " << intValue << std::endl; std::cout << "doubleValue: " << doubleValue << std::endl; std::cout << "stringValue: " << stringValue->ref() << std::endl; std::string serializeResult = gsonObject->toString(); std::cout << "toString: " << serializeResult << std::endl; return 0; } - 按“Esc”键,输入:wq!,按“Enter”保存并退出编辑。
- 编译test.cpp文件,指定输出的可执行文件名称为testDemo。
g++ -o testDemo test.cpp -I./include/kacc_gson_shell -I./include/ -I./util/OmniStream_Java_Basictypes/include/ -I/usr/local/ksl/include -L./output -lkaccgson -L./util/OmniStream_Java_Basictypes/lib/ -lJavaBasictypes -lJavaFunctions -L/usr/local/ksl/lib -lKHSEL_ops
OmniStream_Java_Basictypes为OmniStream的Java基础库相关头文件和库文件, /usr/local/ksl为鲲鹏系统库相关头文件和库文件
- 执行可执行文件testDemo。
./testDemo
输出回显信息如下所示。intValue: 42 doubleValue: 3.14 stringValue: Hello, World! toString: {"intValue":42,"longValue":1726819335,"shortValue":996,"doubleValue":3.14,"floatValue":0.00159,"stringValue":"Hello, World!","stringValueFromInt64":1726819335,"arrayValue":[1,2,3],"boolValue":true,"objectValue":{"nestedInt":100,"nestedString":"Nested"},"arrayObject":[{"name":"hua","age":18},{"name":"wei","age":20}]}