proxygen
proxygen/folly/folly/docs/DynamicConverter.md
Go to the documentation of this file.
1 `folly/DynamicConverter.h`
2 --------------------------
3 
4 When dynamic objects contain data of a known type, it is sometimes
5 useful to have its well-typed representation. A broad set of
6 type-conversions are contained in `DynamicConverter.h`, and
7 facilitate the transformation of dynamic objects into their well-typed
8 format.
9 
10 ### Usage
11 ***
12 
13 Simply pass a dynamic into a templated convertTo:
14 
15 ```
16  dynamic d = { { 1, 2, 3 }, { 4, 5 } }; // a vector of vector of int
17  auto vvi = convertTo<fbvector<fbvector<int>>>(d);
18 ```
19 
20 ### Supported Types
21 ***
22 
23 convertTo naturally supports conversions to
24 
25 1. arithmetic types (such as int64_t, unsigned short, bool, and double)
26 2. fbstring, std::string
27 3. containers and map-containers
28 
29 NOTE:
30 
31 convertTo<Type> will assume that Type is a container if
32 * it has a Type::value_type, and
33 * it has a Type::iterator, and
34 * it has a constructor that accepts two InputIterators
35 
36 Additionally, convertTo<Type> will assume that Type is a map if
37 * it has a Type::key_type, and
38 * it has a Type::mapped_type, and
39 * value_type is a pair of const key_type and mapped_type
40 
41 If Type meets the container criteria, then it will be constructed
42 by calling its InputIterator constructor.
43 
44 ### Customization
45 ***
46 
47 If you want to use convertTo to convert dynamics into your own custom
48 class, then all you have to do is provide a template specialization
49 of DynamicConverter with the static method convert. Make sure you put it
50 in namespace folly.
51 
52 Example:
53 
54 ``` Cpp
55  struct Token {
56  int kind_;
57  fbstring lexeme_;
58 
59  explicit Token(int kind, const fbstring& lexeme)
60  : kind_(kind), lexeme_(lexeme) {}
61  };
62  namespace folly {
63  template <> struct DynamicConverter<Token> {
64  static Token convert(const dynamic& d) {
65  int k = convertTo<int>(d["KIND"]);
66  fbstring lex = convertTo<fbstring>(d["LEXEME"]);
67  return Token(k, lex);
68  }
69  };
70  }
71 ```