Skip to content

Instantly share code, notes, and snippets.

@makomweb
Last active June 2, 2022 16:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save makomweb/6660418 to your computer and use it in GitHub Desktop.
Save makomweb/6660418 to your computer and use it in GitHub Desktop.
Some fun with JSON serialization/deserialization using C++ REST SDK (Codename "Casablanca").
#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;
}
@gitChinmay
Copy link

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

@balamcsd
Copy link

balamcsd commented Feb 24, 2018

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