Last active
June 2, 2022 16:35
-
-
Save makomweb/6660418 to your computer and use it in GitHub Desktop.
Some fun with JSON serialization/deserialization using C++ REST SDK (Codename "Casablanca").
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cpprest/json.h> | |
#include <sstream> | |
using namespace std; | |
typedef web::json::value JsonValue; | |
typedef web::json::value::value_type JsonValueType; | |
typedef std::wstring String; | |
typedef std::wstringstream StringStream; | |
String JsonValueTypeToString(const JsonValueType& type) | |
{ | |
switch (type) | |
{ | |
case JsonValueType::Array: return L"Array"; | |
case JsonValueType::Boolean: return L"Boolean"; | |
case JsonValueType::Null: return L"Null"; | |
case JsonValueType::Number: return L"Number"; | |
case JsonValueType::Object: return L"Object"; | |
case JsonValueType::String: return L"String"; | |
} | |
} | |
void Externalize(const JsonValue& json) | |
{ | |
for (auto iter = json.cbegin(); iter != json.cend(); ++iter) | |
{ | |
auto k = iter->first; | |
auto v = iter->second; | |
auto key = k.as_string(); | |
auto value = v.to_string(); | |
wcout << key << L" : " << value << " (" << JsonValueTypeToString(v.type()) << ")" << endl; | |
} | |
} | |
void Test1_json_serialize() | |
{ | |
JsonValue json; | |
json[L"key1"] = JsonValue::boolean(false); | |
json[L"key2"] = JsonValue::number(44); | |
json[L"key3"] = JsonValue::number(43.6); | |
json[L"key4"] = JsonValue::string(U("str")); | |
Externalize(json); | |
json.serialize(wcout); | |
} | |
void Test2_json_deserialize() | |
{ | |
StringStream ss; | |
ss << U("{\"key1\":false,\"key2\":44,\"key3\":43.6,\"key4\":\"str\"}"); | |
JsonValue json = JsonValue::parse(ss); | |
Externalize(json); | |
json.serialize(wcout); | |
} | |
int main() | |
{ | |
wcout << "Running test 1" << endl; | |
Test1_json_serialize(); | |
wcout << endl << "Running test 2" << endl; | |
Test2_json_deserialize(); | |
return 0; | |
} |
Hi,
It is saying compile error class "web::json::value" has no member "cbegin" & "cend"
changed json.as_object().cbegin() and json.as_object().cend()
now it is complaining class "std::basic_string" has no member as_string
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice little piece of code!
The documentation is not fully updated making it a little time consuming.
But this saved a lot of time.
Thanks