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_BOOSTJSON_TRAITS_H
2#define JWT_CPP_BOOSTJSON_TRAITS_H
3
4#define JWT_DISABLE_PICOJSON
5#include "jwt-cpp/jwt.h"
6
7#include <boost/json.hpp>
8// if not boost JSON standalone then error...
9
10namespace jwt {
14 namespace traits {
15 namespace json = boost::json;
17 struct boost_json {
18 using value_type = json::value;
19 using object_type = json::object;
20 using array_type = json::array;
21 using string_type = std::string;
22 using number_type = double;
23 using integer_type = std::int64_t;
24 using boolean_type = bool;
25
26 static jwt::json::type get_type(const value_type& val) {
27 using jwt::json::type;
28
29 if (val.kind() == json::kind::bool_) return type::boolean;
30 if (val.kind() == json::kind::int64) return type::integer;
31 if (val.kind() == json::kind::uint64) // boost internally tracks two types of integers
32 return type::integer;
33 if (val.kind() == json::kind::double_) return type::number;
34 if (val.kind() == json::kind::string) return type::string;
35 if (val.kind() == json::kind::array) return type::array;
36 if (val.kind() == json::kind::object) return type::object;
37
38 throw std::logic_error("invalid type");
39 }
40
41 static object_type as_object(const value_type& val) {
42 if (val.kind() != json::kind::object) throw std::bad_cast();
43 return val.get_object();
44 }
45
46 static array_type as_array(const value_type& val) {
47 if (val.kind() != json::kind::array) throw std::bad_cast();
48 return val.get_array();
49 }
50
51 static string_type as_string(const value_type& val) {
52 if (val.kind() != json::kind::string) throw std::bad_cast();
53 return string_type{val.get_string()};
54 }
55
56 static integer_type as_integer(const value_type& val) {
57 switch (val.kind()) {
58 case json::kind::int64: return val.get_int64();
59 case json::kind::uint64: return static_cast<int64_t>(val.get_uint64());
60 default: throw std::bad_cast();
61 }
62 }
63
64 static boolean_type as_boolean(const value_type& val) {
65 if (val.kind() != json::kind::bool_) throw std::bad_cast();
66 return val.get_bool();
67 }
68
69 static number_type as_number(const value_type& val) {
70 if (val.kind() != json::kind::double_) throw std::bad_cast();
71 return val.get_double();
72 }
73
74 static bool parse(value_type& val, string_type str) {
75 val = json::parse(str);
76 return true;
77 }
78
79 static std::string serialize(const value_type& val) { return json::serialize(val); }
80 };
81 } // namespace traits
82} // namespace jwt
83
84#endif // JWT_CPP_BOOSTJSON_TRAITS_H
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 Boost.JSON
Definition traits.h:17