CodeBlanks Logo Icon CodeBlanks

Summary - Serialization

Combine binary, JSON and versioning to write a config file.

Summary: a configuration file

In this summary you will combine binary, JSON and versioning for a configuration file. You will serialize the name and value fields of a Config struct as JSON and add a version field.

With the JSON library you create a nlohmann::json object. You set the j["name"], j["value"] and j["version"] fields. j.dump() produces the configuration file as a string. This is both human readable and version aware; it is a common approach in real projects.

Practice Write a versioned JSON configuration

Add #include <nlohmann/json.hpp>. Define nlohmann::json j;. Set j["name"] = "Alex";, j["value"] = 42; and j["version"] = 1;. Print with std::cout << j.dump();.

Starter code

main.cpp
#include <iostream>
#include <string>

// Add the nlohmann/json header and versioned JSON

int main() {
    // Create JSON, add a version and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <nlohmann/json.hpp>

int main() {
    nlohmann::json j;
    j["name"] = "Alex";
    j["value"] = 42;
    j["version"] = 1;
    std::cout << j.dump();
    return 0;
}

Expected output

{"name":"Alex","value":42,"version":1}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What do JSON + versioning provide?

  • Binary only data
  • Faster compilation
  • Readable and versioned configuration Correct answer
  • Less memory

Explanation: JSON is readable, versioning adds version control.

2 Complete the dump call

Question
std::cout << j.____();
Answer
std::cout << j.dump();

Explanation: j.dump() returns the JSON object as a string.

3 Match the method to its role

Term Meaning
binary write Writes bytes
text << >> Writes/reads text
nlohmann::json JSON object
version field Version check

All lessons in Advanced