AnCH Framework 0.2
Another C++ Hack: C++23 utility libraries
Loading...
Searching...
No Matches
AnCH JSON library documentation

Introduction

AnCH JSON library is JSON serialization and deserialization library for JSON format.

Prerequisites

AnCH JSON is a standalone library.

Installation

CMake target anch::json:

find_package(Anch REQUIRED)
target_link_libraries(my-app PRIVATE anch::json)

See installation.

Conception

Serialized fields are declared by the description of each type shared by formats: an anch::Mapping specialization (anch-utils, mapping.hpp , see AnCH utils library documentation ) whose registerObject function registers the fields with their JSON key and their member pointer (or a getter and / or a setter). std::optional , pointers, collections and maps fields are mapped with the mapper of their value type.

anch::json::serialize writes JSON in a stream or returns a string ; anch::json::deserialize reads a stream and raises anch::json::MappingError on invalid JSON (with its position). Mapping options (anch::json::MappingOptions ) control unknown fields, null values and limits (depth, payload size).
With ANCH_UUID and ANCH_DATE options, anch::UUID , anch::date::DateTime and anch::date::Date and anch::date::Time are mapped as strings (RFC 3339 for dates and times).

Examples

#include "json/json.hpp"
#include <iostream>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
struct Pet {
uint64_t id;
std::string name;
std::vector<std::string> tags;
std::optional<std::string> owner;
};
// Declare serialized fields (once per type)
template<>
struct anch::Mapping<Pet> {
static void
registerObject(anch::ObjectMapper<Pet> auto& mapper) {
mapper
.registerField("id", &Pet::id)
.registerField("name", &Pet::name)
.registerField("tags", &Pet::tags) // container: element type is given
.registerField("owner", &Pet::owner); // std::optional: value type is given too
}
};
int
main() {
Pet pet{1, "Rex", {"dog", "good boy"}, std::nullopt};
std::string json = anch::json::serialize(pet);
std::cout << json << std::endl;
std::istringstream input(R"({"id":2,"name":"Médor","tags":["cat"],"owner":"Vincent"})");
Pet parsed = anch::json::deserialize<Pet>(input); // anch::json::MappingError when invalid
std::cout << parsed.name << " " << parsed.owner.value_or("-") << std::endl;
return 0;
}

Output:

{"id":1,"name":"Rex","tags":["dog","good boy"]}
Médor Vincent

Required fields and error path

Constraints can be given when a field is registered. anch::val::required checks on deserialization that the field is present (error code MISSING_FIELD , every missing field is listed in the message) and that its value is not null , unless the field can hold null ( std::optional , std::shared_ptr , std::unique_ptr or pointer ; error code CONSTRAINT_VIOLATION ). Fields which are not required are not checked: a null value leaves them unchanged.

anch::json::MappingError::getPath gives the JSON Pointer (RFC 6901) of the value in error, from the deserialized root value ; what() starts with this path.

struct Pet {
uint64_t id;
std::string name;
std::optional<std::string> owner;
};
struct Shelter {
std::vector<Pet> pets;
};
template<>
struct anch::Mapping<Pet> {
static void
registerObject(anch::ObjectMapper<Pet> auto& mapper) {
mapper
.registerField("id", &Pet::id, anch::val::required)
.registerField("name", &Pet::name, anch::val::required)
.registerField("owner", &Pet::owner, anch::val::required); // has to be present, can be null
}
};
template<>
struct anch::Mapping<Shelter> {
static void
registerObject(anch::ObjectMapper<Shelter> auto& mapper) {
mapper
.registerField("pets", &Shelter::pets, anch::val::required);
}
};
int
main() {
for(const char* json : {R"({"pets":[{"id":1,"name":"Rex","owner":null},{"id":2,"owner":"Vincent"}]})",
R"({"pets":[{"id":1,"name":null,"owner":null}]})"}) {
try {
std::istringstream input(json);
[[maybe_unused]] Shelter shelter = anch::json::deserialize<Shelter>(input);
} catch(const anch::json::MappingError& error) {
std::cout << error.getPath() << " -> " << error.what() << std::endl;
}
}
return 0;
}

Output:

/pets/1 -> /pets/1: Missing required field 'name' near '"Vincent"}]}'
/pets/0/name -> /pets/0/name: Required field can not be null near 'name":null,"owner":n'

Value constraints

Value constraints of anch-val (see AnCH validation library documentation , header val/constraints.hpp ) are given at registration too. They are checked after the field value has been read and raise anch::json::MappingError with CONSTRAINT_VIOLATION error code. null and absent values are not checked ( anch::val::required checks presence). Constraints are checked at compile time against the field type: minLength on an integer field does not compile.

struct Pet {
std::string name;
int32_t age;
std::vector<std::string> tags;
std::map<std::string,int64_t> scores;
std::optional<std::string> color;
};
template<>
struct anch::Mapping<Pet> {
static void
registerObject(anch::ObjectMapper<Pet> auto& mapper) {
mapper
.registerField("name", &Pet::name, anch::val::required, anch::val::minLength(1), anch::val::maxLength(32))
.registerField("age", &Pet::age, anch::val::minimum(0), anch::val::maximum(50))
.registerField("tags", &Pet::tags, anch::val::maxItems(5), anch::val::uniqueItems,
anch::val::items(anch::val::minLength(1))) // checked on every tag
.registerField("scores", &Pet::scores, anch::val::items(anch::val::multipleOf(5)))
.registerField("color", &Pet::color, anch::val::allowed({"black", "white"})); // checked when not null
}
};
int
main() {
for(const char* json : {R"({"name":"Rex","age":3,"tags":["dog",""]})",
R"({"name":"Rex","age":3,"scores":{"agility":12}})",
R"({"name":"Rex","age":-1})",
R"({"name":"Rex","color":"brown"})"}) {
try {
std::istringstream input(json);
[[maybe_unused]] Pet pet = anch::json::deserialize<Pet>(input);
} catch(const anch::json::MappingError& error) {
std::cout << error.what() << std::endl;
}
}
return 0;
}

Output:

/tags/1: Length 0 is lower than minLength 1 near '["dog",""]}'
/scores/agility: Value 12 is not a multiple of 5 near 'ility":12}}'
/age: Value -1 is lower than minimum 0 near '","age":-1}'
/color: Value 'brown' is not allowed (allowed: 'black', 'white') near 'r":"brown"}'

Constraints checks on deserialization and serialization

Constraints ( anch::val::required and value constraints) are checked according to mapping options:

  • deserialize_check_constraints (default true ): after values have been read ;
  • serialize_check_constraints (default false ): before values are written. The error has no input excerpt (message is "<path>: <constraint message>" ) and the output contains the JSON written before the error.

Required fields are always written, even when empty: null for empty std::optional and pointers, [] and {} for empty containers, whatever serialize_null and serialize_empty_col options are (the document would be refused by the other side otherwise).

Server side checks what it receives and trusts what it builds (default options). Client side checks what it sends and trusts server responses:

client.serialize_check_constraints = true; // invalid requests are not sent
client.deserialize_check_constraints = false; // responses are trusted

Validation

anch::val::validate (anch-val, val/validation.hpp , see AnCH validation library documentation ) checks an object without serializing it: constraints of its fields and of its nested values, every violation is returned with its path. Mapping options are not used.

struct Pet {
std::string name;
int32_t age = 0;
std::vector<std::string> tags;
};
struct Shelter {
std::vector<Pet> pets;
};
template<>
struct anch::Mapping<Pet> {
static void
registerObject(anch::ObjectMapper<Pet> auto& mapper) {
mapper
.registerField("name", &Pet::name, anch::val::required, anch::val::minLength(1))
.registerField("age", &Pet::age, anch::val::minimum(0))
.registerField("tags", &Pet::tags, anch::val::items(anch::val::minLength(1)));
}
};
template<>
struct anch::Mapping<Shelter> {
static void
registerObject(anch::ObjectMapper<Shelter> auto& mapper) {
mapper
.registerField("pets", &Shelter::pets, anch::val::maxItems(10));
}
};
int
main() {
Shelter shelter{{Pet{"Rex", 3, {"dog"}}, Pet{"", -1, {"cat", ""}}}};
for(const anch::val::Violation& violation : anch::val::validate(shelter)) { // every violation
std::cout << violation.path << ": " << violation.message << std::endl;
}
return 0;
}

Output:

/pets/1/name: Length 0 is lower than minLength 1
/pets/1/age: Value -1 is lower than minimum 0
/pets/1/tags/1: Length 0 is lower than minLength 1