Skip to content

snorrwe/minijson

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MiniJson

Build Status codecov

Lightweight header-only JSON library written in C++17. Just include the headers and you're good to go. MiniJSON is a very opinionated framework for parsing JSON. MiniJSON might be a suitable for your application if your JSON communication has a very strict schema.

Requirements

  • C++17 compatible compiler

Usage

To be able to parse custom data structures the structures must provide a static constexpr method named json_propertied that returns a tuple of the public data members that we wish to serialise / parse.

struct Seed
{
    // Serialisable data members must be declared public
    float radius = 0.0;

    constexpr static auto json_properties()
    {
        return std::make_tuple(mini_json::property(&Seed::radius, "radius"));
    }
};

Usage example

#include "json.h"

struct Seed
{
    float radius = 0.0;

    constexpr static auto json_properties()
    {
        return std::make_tuple(mini_json::property(&Seed::radius, "radius"));
    }
};

struct Apple
{
    std::string color = "";
    int size = 0;
    Seed seed;

    constexpr static auto json_properties()
    {
        return std::make_tuple(mini_json::property(&Apple::color, "color"),
                               mini_json::property(&Apple::seed, "seed"),
                               mini_json::property(&Apple::size, "size"));
    }
};

TEST_F(TestJsonParser, CanReadJsonIntoObject)
{
    /*
    {
        "color":"red",
        "size": -25,
        "seed": {
            "radius": -3.14
        }
    }
    */
    const auto json = "{\"color\":\"red\",\"size\": -25,\"seed\":{\"radius\":-3.14}}"s;

    auto result = mini_json::parse<Apple>(json.begin(), json.end());

    EXPECT_EQ(result.color, "red");
    EXPECT_EQ(result.size, -25);
    EXPECT_FLOAT_EQ(result.seed.radius, -3.14f);
}

Supported types:

  • Any T that implements the json_properties static member function
  • std::vector<T> for any json serialisable T
  • std::string
  • int
  • size_t
  • float
  • double

Limitations:

  • std::tuple is not yet supported.
  • Optional fields are not supported.