JWT-CPP v0.7.0
A header only library for creating and validating JSON Web Tokens (JWT) in C++
Loading...
Searching...
No Matches
traits.h
1#ifndef JWT_CPP_NLOHMANN_JSON_TRAITS_H
2#define JWT_CPP_NLOHMANN_JSON_TRAITS_H
3
4#include "jwt-cpp/jwt.h"
5#include "nlohmann/json.hpp"
6
7namespace jwt {
11 namespace traits {
14 using json = nlohmann::json;
15 using value_type = json;
16 using object_type = json::object_t;
17 using array_type = json::array_t;
18 using string_type = std::string; // current limitation of traits implementation
19 using number_type = json::number_float_t;
20 using integer_type = json::number_integer_t;
21 using boolean_type = json::boolean_t;
22
23 static jwt::json::type get_type(const json& val) {
24 using jwt::json::type;
25
26 if (val.type() == json::value_t::boolean) return type::boolean;
27 // nlohmann internally tracks two types of integers
28 if (val.type() == json::value_t::number_integer) return type::integer;
29 if (val.type() == json::value_t::number_unsigned) return type::integer;
30 if (val.type() == json::value_t::number_float) return type::number;
31 if (val.type() == json::value_t::string) return type::string;
32 if (val.type() == json::value_t::array) return type::array;
33 if (val.type() == json::value_t::object) return type::object;
34
35 throw std::logic_error("invalid type");
36 }
37
38 static json::object_t as_object(const json& val) {
39 if (val.type() != json::value_t::object) throw std::bad_cast();
40 return val.get<json::object_t>();
41 }
42
43 static std::string as_string(const json& val) {
44 if (val.type() != json::value_t::string) throw std::bad_cast();
45 return val.get<std::string>();
46 }
47
48 static json::array_t as_array(const json& val) {
49 if (val.type() != json::value_t::array) throw std::bad_cast();
50 return val.get<json::array_t>();
51 }
52
53 static int64_t as_integer(const json& val) {
54 switch (val.type()) {
55 case json::value_t::number_integer:
56 case json::value_t::number_unsigned: return val.get<int64_t>();
57 default: throw std::bad_cast();
58 }
59 }
60
61 static bool as_boolean(const json& val) {
62 if (val.type() != json::value_t::boolean) throw std::bad_cast();
63 return val.get<bool>();
64 }
65
66 static double as_number(const json& val) {
67 if (val.type() != json::value_t::number_float) throw std::bad_cast();
68 return val.get<double>();
69 }
70
71 static bool parse(json& val, std::string str) {
72 val = json::parse(str.begin(), str.end());
73 return true;
74 }
75
76 static std::string serialize(const json& val) { return val.dump(); }
77 };
78 } // namespace traits
79} // namespace jwt
80
81#endif
type
Categories for the various JSON types used in JWTs.
Definition jwt.h:2274
JSON Web Token.
Definition base.h:21
basic_claim's JSON trait implementation for Modern C++ JSON
Definition traits.h:13