Usage Example
This section provides a complete example of using KACC_JSON interfaces.
- Create a test.cpp file.
vi test.cpp
- Press i to enter the insert mode and add the following content to the file:
#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; } - Press Esc, type :wq!, and press Enter to save the file and exit.
- Compile the test.cpp file and specify the name of the output executable file as 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 contains header files and library files related to the Java basic libraries of OmniStream. /usr/local/ksl contains header files and library files related to KSL.
- Run the testDemo executable file.
./testDemo
The command output is as follows: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}]}