json_value_converter.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_JSON_JSON_VALUE_CONVERTER_H_
  5. #define BASE_JSON_JSON_VALUE_CONVERTER_H_
  6. #include <stddef.h>
  7. #include <memory>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/base_export.h"
  12. #include "base/logging.h"
  13. #include "base/memory/ptr_util.h"
  14. #include "base/strings/string_piece.h"
  15. #include "base/values.h"
  16. // JSONValueConverter converts a JSON value into a C++ struct in a
  17. // lightweight way.
  18. //
  19. // Usage:
  20. // For real examples, you may want to refer to _unittest.cc file.
  21. //
  22. // Assume that you have a struct like this:
  23. // struct Message {
  24. // int foo;
  25. // std::string bar;
  26. // static void RegisterJSONConverter(
  27. // JSONValueConverter<Message>* converter);
  28. // };
  29. //
  30. // And you want to parse a json data into this struct. First, you
  31. // need to declare RegisterJSONConverter() method in your struct.
  32. // // static
  33. // void Message::RegisterJSONConverter(
  34. // JSONValueConverter<Message>* converter) {
  35. // converter->RegisterIntField("foo", &Message::foo);
  36. // converter->RegisterStringField("bar", &Message::bar);
  37. // }
  38. //
  39. // Then, you just instantiate your JSONValueConverter of your type and call
  40. // Convert() method.
  41. // Message message;
  42. // JSONValueConverter<Message> converter;
  43. // converter.Convert(json, &message);
  44. //
  45. // Convert() returns false when it fails. Here "fail" means that the value is
  46. // structurally different from expected, such like a string value appears
  47. // for an int field. Do not report failures for missing fields.
  48. // Also note that Convert() will modify the passed |message| even when it
  49. // fails for performance reason.
  50. //
  51. // For nested field, the internal message also has to implement the registration
  52. // method. Then, just use RegisterNestedField() from the containing struct's
  53. // RegisterJSONConverter method.
  54. // struct Nested {
  55. // Message foo;
  56. // static void RegisterJSONConverter(...) {
  57. // ...
  58. // converter->RegisterNestedField("foo", &Nested::foo);
  59. // }
  60. // };
  61. //
  62. // For repeated field, we just assume std::vector<std::unique_ptr<ElementType>>
  63. // for its container and you can put RegisterRepeatedInt or some other types.
  64. // Use RegisterRepeatedMessage for nested repeated fields.
  65. //
  66. // Sometimes JSON format uses string representations for other types such
  67. // like enum, timestamp, or URL. You can use RegisterCustomField method
  68. // and specify a function to convert a StringPiece to your type.
  69. // bool ConvertFunc(StringPiece s, YourEnum* result) {
  70. // // do something and return true if succeed...
  71. // }
  72. // struct Message {
  73. // YourEnum ye;
  74. // ...
  75. // static void RegisterJSONConverter(...) {
  76. // ...
  77. // converter->RegsiterCustomField<YourEnum>(
  78. // "your_enum", &Message::ye, &ConvertFunc);
  79. // }
  80. // };
  81. namespace base {
  82. template <typename StructType>
  83. class JSONValueConverter;
  84. namespace internal {
  85. template <typename StructType>
  86. class FieldConverterBase {
  87. public:
  88. explicit FieldConverterBase(const std::string& path) : field_path_(path) {}
  89. FieldConverterBase(const FieldConverterBase&) = delete;
  90. FieldConverterBase& operator=(const FieldConverterBase&) = delete;
  91. virtual ~FieldConverterBase() = default;
  92. virtual bool ConvertField(const base::Value& value,
  93. StructType* obj) const = 0;
  94. const std::string& field_path() const { return field_path_; }
  95. private:
  96. std::string field_path_;
  97. };
  98. template <typename FieldType>
  99. class ValueConverter {
  100. public:
  101. virtual ~ValueConverter() = default;
  102. virtual bool Convert(const base::Value& value, FieldType* field) const = 0;
  103. };
  104. template <typename StructType, typename FieldType>
  105. class FieldConverter : public FieldConverterBase<StructType> {
  106. public:
  107. explicit FieldConverter(const std::string& path,
  108. FieldType StructType::*field,
  109. ValueConverter<FieldType>* converter)
  110. : FieldConverterBase<StructType>(path),
  111. field_pointer_(field),
  112. value_converter_(converter) {}
  113. FieldConverter(const FieldConverter&) = delete;
  114. FieldConverter& operator=(const FieldConverter&) = delete;
  115. bool ConvertField(const base::Value& value, StructType* dst) const override {
  116. return value_converter_->Convert(value, &(dst->*field_pointer_));
  117. }
  118. private:
  119. FieldType StructType::*field_pointer_;
  120. std::unique_ptr<ValueConverter<FieldType>> value_converter_;
  121. };
  122. template <typename FieldType>
  123. class BasicValueConverter;
  124. template <>
  125. class BASE_EXPORT BasicValueConverter<int> : public ValueConverter<int> {
  126. public:
  127. BasicValueConverter() = default;
  128. BasicValueConverter(const BasicValueConverter&) = delete;
  129. BasicValueConverter& operator=(const BasicValueConverter&) = delete;
  130. bool Convert(const base::Value& value, int* field) const override;
  131. };
  132. template <>
  133. class BASE_EXPORT BasicValueConverter<std::string>
  134. : public ValueConverter<std::string> {
  135. public:
  136. BasicValueConverter() = default;
  137. BasicValueConverter(const BasicValueConverter&) = delete;
  138. BasicValueConverter& operator=(const BasicValueConverter&) = delete;
  139. bool Convert(const base::Value& value, std::string* field) const override;
  140. };
  141. template <>
  142. class BASE_EXPORT BasicValueConverter<std::u16string>
  143. : public ValueConverter<std::u16string> {
  144. public:
  145. BasicValueConverter() = default;
  146. BasicValueConverter(const BasicValueConverter&) = delete;
  147. BasicValueConverter& operator=(const BasicValueConverter&) = delete;
  148. bool Convert(const base::Value& value, std::u16string* field) const override;
  149. };
  150. template <>
  151. class BASE_EXPORT BasicValueConverter<double> : public ValueConverter<double> {
  152. public:
  153. BasicValueConverter() = default;
  154. BasicValueConverter(const BasicValueConverter&) = delete;
  155. BasicValueConverter& operator=(const BasicValueConverter&) = delete;
  156. bool Convert(const base::Value& value, double* field) const override;
  157. };
  158. template <>
  159. class BASE_EXPORT BasicValueConverter<bool> : public ValueConverter<bool> {
  160. public:
  161. BasicValueConverter() = default;
  162. BasicValueConverter(const BasicValueConverter&) = delete;
  163. BasicValueConverter& operator=(const BasicValueConverter&) = delete;
  164. bool Convert(const base::Value& value, bool* field) const override;
  165. };
  166. template <typename FieldType>
  167. class ValueFieldConverter : public ValueConverter<FieldType> {
  168. public:
  169. typedef bool (*ConvertFunc)(const base::Value* value, FieldType* field);
  170. explicit ValueFieldConverter(ConvertFunc convert_func)
  171. : convert_func_(convert_func) {}
  172. ValueFieldConverter(const ValueFieldConverter&) = delete;
  173. ValueFieldConverter& operator=(const ValueFieldConverter&) = delete;
  174. bool Convert(const base::Value& value, FieldType* field) const override {
  175. return convert_func_(&value, field);
  176. }
  177. private:
  178. ConvertFunc convert_func_;
  179. };
  180. template <typename FieldType>
  181. class CustomFieldConverter : public ValueConverter<FieldType> {
  182. public:
  183. typedef bool (*ConvertFunc)(StringPiece value, FieldType* field);
  184. explicit CustomFieldConverter(ConvertFunc convert_func)
  185. : convert_func_(convert_func) {}
  186. CustomFieldConverter(const CustomFieldConverter&) = delete;
  187. CustomFieldConverter& operator=(const CustomFieldConverter&) = delete;
  188. bool Convert(const base::Value& value, FieldType* field) const override {
  189. return value.is_string() && convert_func_(value.GetString(), field);
  190. }
  191. private:
  192. ConvertFunc convert_func_;
  193. };
  194. template <typename NestedType>
  195. class NestedValueConverter : public ValueConverter<NestedType> {
  196. public:
  197. NestedValueConverter() = default;
  198. NestedValueConverter(const NestedValueConverter&) = delete;
  199. NestedValueConverter& operator=(const NestedValueConverter&) = delete;
  200. bool Convert(const base::Value& value, NestedType* field) const override {
  201. return converter_.Convert(value, field);
  202. }
  203. private:
  204. JSONValueConverter<NestedType> converter_;
  205. };
  206. template <typename Element>
  207. class RepeatedValueConverter
  208. : public ValueConverter<std::vector<std::unique_ptr<Element>>> {
  209. public:
  210. RepeatedValueConverter() = default;
  211. RepeatedValueConverter(const RepeatedValueConverter&) = delete;
  212. RepeatedValueConverter& operator=(const RepeatedValueConverter&) = delete;
  213. bool Convert(const base::Value& value,
  214. std::vector<std::unique_ptr<Element>>* field) const override {
  215. const Value::List* list = value.GetIfList();
  216. if (!list) {
  217. // The field is not a list.
  218. return false;
  219. }
  220. field->reserve(list->size());
  221. size_t i = 0;
  222. for (const Value& element : *list) {
  223. auto e = std::make_unique<Element>();
  224. if (basic_converter_.Convert(element, e.get())) {
  225. field->push_back(std::move(e));
  226. } else {
  227. DVLOG(1) << "failure at " << i << "-th element";
  228. return false;
  229. }
  230. i++;
  231. }
  232. return true;
  233. }
  234. private:
  235. BasicValueConverter<Element> basic_converter_;
  236. };
  237. template <typename NestedType>
  238. class RepeatedMessageConverter
  239. : public ValueConverter<std::vector<std::unique_ptr<NestedType>>> {
  240. public:
  241. RepeatedMessageConverter() = default;
  242. RepeatedMessageConverter(const RepeatedMessageConverter&) = delete;
  243. RepeatedMessageConverter& operator=(const RepeatedMessageConverter&) = delete;
  244. bool Convert(const base::Value& value,
  245. std::vector<std::unique_ptr<NestedType>>* field) const override {
  246. const Value::List* list = value.GetIfList();
  247. if (!list)
  248. return false;
  249. field->reserve(list->size());
  250. size_t i = 0;
  251. for (const Value& element : *list) {
  252. auto nested = std::make_unique<NestedType>();
  253. if (converter_.Convert(element, nested.get())) {
  254. field->push_back(std::move(nested));
  255. } else {
  256. DVLOG(1) << "failure at " << i << "-th element";
  257. return false;
  258. }
  259. i++;
  260. }
  261. return true;
  262. }
  263. private:
  264. JSONValueConverter<NestedType> converter_;
  265. };
  266. template <typename NestedType>
  267. class RepeatedCustomValueConverter
  268. : public ValueConverter<std::vector<std::unique_ptr<NestedType>>> {
  269. public:
  270. typedef bool (*ConvertFunc)(const base::Value* value, NestedType* field);
  271. explicit RepeatedCustomValueConverter(ConvertFunc convert_func)
  272. : convert_func_(convert_func) {}
  273. RepeatedCustomValueConverter(const RepeatedCustomValueConverter&) = delete;
  274. RepeatedCustomValueConverter& operator=(const RepeatedCustomValueConverter&) =
  275. delete;
  276. bool Convert(const base::Value& value,
  277. std::vector<std::unique_ptr<NestedType>>* field) const override {
  278. const Value::List* list = value.GetIfList();
  279. if (!list)
  280. return false;
  281. field->reserve(list->size());
  282. size_t i = 0;
  283. for (const Value& element : *list) {
  284. auto nested = std::make_unique<NestedType>();
  285. if ((*convert_func_)(&element, nested.get())) {
  286. field->push_back(std::move(nested));
  287. } else {
  288. DVLOG(1) << "failure at " << i << "-th element";
  289. return false;
  290. }
  291. i++;
  292. }
  293. return true;
  294. }
  295. private:
  296. ConvertFunc convert_func_;
  297. };
  298. } // namespace internal
  299. template <class StructType>
  300. class JSONValueConverter {
  301. public:
  302. JSONValueConverter() { StructType::RegisterJSONConverter(this); }
  303. JSONValueConverter(const JSONValueConverter&) = delete;
  304. JSONValueConverter& operator=(const JSONValueConverter&) = delete;
  305. void RegisterIntField(const std::string& field_name, int StructType::*field) {
  306. fields_.push_back(
  307. std::make_unique<internal::FieldConverter<StructType, int>>(
  308. field_name, field, new internal::BasicValueConverter<int>));
  309. }
  310. void RegisterStringField(const std::string& field_name,
  311. std::string StructType::*field) {
  312. fields_.push_back(
  313. std::make_unique<internal::FieldConverter<StructType, std::string>>(
  314. field_name, field, new internal::BasicValueConverter<std::string>));
  315. }
  316. void RegisterStringField(const std::string& field_name,
  317. std::u16string StructType::*field) {
  318. fields_.push_back(
  319. std::make_unique<internal::FieldConverter<StructType, std::u16string>>(
  320. field_name, field,
  321. new internal::BasicValueConverter<std::u16string>));
  322. }
  323. void RegisterBoolField(const std::string& field_name,
  324. bool StructType::*field) {
  325. fields_.push_back(
  326. std::make_unique<internal::FieldConverter<StructType, bool>>(
  327. field_name, field, new internal::BasicValueConverter<bool>));
  328. }
  329. void RegisterDoubleField(const std::string& field_name,
  330. double StructType::*field) {
  331. fields_.push_back(
  332. std::make_unique<internal::FieldConverter<StructType, double>>(
  333. field_name, field, new internal::BasicValueConverter<double>));
  334. }
  335. template <class NestedType>
  336. void RegisterNestedField(const std::string& field_name,
  337. NestedType StructType::*field) {
  338. fields_.push_back(
  339. std::make_unique<internal::FieldConverter<StructType, NestedType>>(
  340. field_name, field, new internal::NestedValueConverter<NestedType>));
  341. }
  342. template <typename FieldType>
  343. void RegisterCustomField(const std::string& field_name,
  344. FieldType StructType::*field,
  345. bool (*convert_func)(StringPiece, FieldType*)) {
  346. fields_.push_back(
  347. std::make_unique<internal::FieldConverter<StructType, FieldType>>(
  348. field_name, field,
  349. new internal::CustomFieldConverter<FieldType>(convert_func)));
  350. }
  351. template <typename FieldType>
  352. void RegisterCustomValueField(const std::string& field_name,
  353. FieldType StructType::*field,
  354. bool (*convert_func)(const base::Value*,
  355. FieldType*)) {
  356. fields_.push_back(
  357. std::make_unique<internal::FieldConverter<StructType, FieldType>>(
  358. field_name, field,
  359. new internal::ValueFieldConverter<FieldType>(convert_func)));
  360. }
  361. void RegisterRepeatedInt(
  362. const std::string& field_name,
  363. std::vector<std::unique_ptr<int>> StructType::*field) {
  364. fields_.push_back(std::make_unique<internal::FieldConverter<
  365. StructType, std::vector<std::unique_ptr<int>>>>(
  366. field_name, field, new internal::RepeatedValueConverter<int>));
  367. }
  368. void RegisterRepeatedString(
  369. const std::string& field_name,
  370. std::vector<std::unique_ptr<std::string>> StructType::*field) {
  371. fields_.push_back(
  372. std::make_unique<internal::FieldConverter<
  373. StructType, std::vector<std::unique_ptr<std::string>>>>(
  374. field_name, field,
  375. new internal::RepeatedValueConverter<std::string>));
  376. }
  377. void RegisterRepeatedString(
  378. const std::string& field_name,
  379. std::vector<std::unique_ptr<std::u16string>> StructType::*field) {
  380. fields_.push_back(
  381. std::make_unique<internal::FieldConverter<
  382. StructType, std::vector<std::unique_ptr<std::u16string>>>>(
  383. field_name, field,
  384. new internal::RepeatedValueConverter<std::u16string>));
  385. }
  386. void RegisterRepeatedDouble(
  387. const std::string& field_name,
  388. std::vector<std::unique_ptr<double>> StructType::*field) {
  389. fields_.push_back(std::make_unique<internal::FieldConverter<
  390. StructType, std::vector<std::unique_ptr<double>>>>(
  391. field_name, field, new internal::RepeatedValueConverter<double>));
  392. }
  393. void RegisterRepeatedBool(
  394. const std::string& field_name,
  395. std::vector<std::unique_ptr<bool>> StructType::*field) {
  396. fields_.push_back(std::make_unique<internal::FieldConverter<
  397. StructType, std::vector<std::unique_ptr<bool>>>>(
  398. field_name, field, new internal::RepeatedValueConverter<bool>));
  399. }
  400. template <class NestedType>
  401. void RegisterRepeatedCustomValue(
  402. const std::string& field_name,
  403. std::vector<std::unique_ptr<NestedType>> StructType::*field,
  404. bool (*convert_func)(const base::Value*, NestedType*)) {
  405. fields_.push_back(
  406. std::make_unique<internal::FieldConverter<
  407. StructType, std::vector<std::unique_ptr<NestedType>>>>(
  408. field_name, field,
  409. new internal::RepeatedCustomValueConverter<NestedType>(
  410. convert_func)));
  411. }
  412. template <class NestedType>
  413. void RegisterRepeatedMessage(
  414. const std::string& field_name,
  415. std::vector<std::unique_ptr<NestedType>> StructType::*field) {
  416. fields_.push_back(
  417. std::make_unique<internal::FieldConverter<
  418. StructType, std::vector<std::unique_ptr<NestedType>>>>(
  419. field_name, field,
  420. new internal::RepeatedMessageConverter<NestedType>));
  421. }
  422. bool Convert(const base::Value& value, StructType* output) const {
  423. const Value::Dict* dict = value.GetIfDict();
  424. if (!dict)
  425. return false;
  426. for (size_t i = 0; i < fields_.size(); ++i) {
  427. const internal::FieldConverterBase<StructType>* field_converter =
  428. fields_[i].get();
  429. const base::Value* field =
  430. dict->FindByDottedPath(field_converter->field_path());
  431. if (field) {
  432. if (!field_converter->ConvertField(*field, output)) {
  433. DVLOG(1) << "failure at field " << field_converter->field_path();
  434. return false;
  435. }
  436. }
  437. }
  438. return true;
  439. }
  440. private:
  441. std::vector<std::unique_ptr<internal::FieldConverterBase<StructType>>>
  442. fields_;
  443. };
  444. } // namespace base
  445. #endif // BASE_JSON_JSON_VALUE_CONVERTER_H_