mirror of
https://github.com/open-source-parsers/jsoncpp.git
synced 2025-04-21 00:11:50 +02:00

Rewerite and revert some code that this library can be built in pre-C++11 and C++11 env. Main Change List: 1. using -> typedef 2. not using auto & decltype 3. not using raw string literals 4. ..., other c++11 features will be chosen to compile, depending on env.
40 lines
1.1 KiB
C++
40 lines
1.1 KiB
C++
#include "json/json.h"
|
|
#include <cstdlib>
|
|
#include <iostream>
|
|
/**
|
|
* \brief Parse a raw string into Value object using the CharReaderBuilder
|
|
* class, or the legacy Reader class.
|
|
* Example Usage:
|
|
* $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString
|
|
* $./readFromString
|
|
* colin
|
|
* 20
|
|
*/
|
|
int main() {
|
|
const std::string rawJson = "{\"Age\": 20, \"Name\": \"colin\"}";
|
|
const int rawJsonLength = static_cast<int>(rawJson.length());
|
|
JSONCPP_CONST bool shouldUseOldWay = false;
|
|
JSONCPP_STRING err;
|
|
Json::Value root;
|
|
|
|
if (shouldUseOldWay) {
|
|
Json::Reader reader;
|
|
reader.parse(rawJson, root);
|
|
} else {
|
|
Json::CharReaderBuilder builder;
|
|
Json::CharReader* reader(builder.newCharReader());
|
|
if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,
|
|
&err)) {
|
|
std::cout << "error" << std::endl;
|
|
return EXIT_FAILURE;
|
|
}
|
|
delete reader;
|
|
}
|
|
const std::string name = root["Name"].asString();
|
|
const int age = root["Age"].asInt();
|
|
|
|
std::cout << name << std::endl;
|
|
std::cout << age << std::endl;
|
|
return EXIT_SUCCESS;
|
|
}
|