AvTranscoder  0.9.4
C++APIforLibav/FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
JsonWriter.hpp
Go to the documentation of this file.
1 #ifndef _AV_TRANSCODER_MEDIA_PROPERTY_JSONWRITER_HPP_
2 #define _AV_TRANSCODER_MEDIA_PROPERTY_JSONWRITER_HPP_
3 
5 
6 #include <iostream>
7 #include <sstream>
8 
9 namespace avtranscoder
10 {
11 namespace json
12 {
13 
14 /**
15  * @brief To manage 'null' element in JSON
16  */
17 struct JsonNull
18 {
19 };
20 
21 /**
22  * @brief Based class to write element to a stream.
23  */
24 class AvExport JsonStreamWriter
25 {
26 public:
28  : first(true)
29  {
30  }
31  virtual ~JsonStreamWriter() {}
32 
33  virtual std::string build()
34  {
35  finish();
36  return stream.str();
37  }
38 
39 protected:
40  friend class JsonObjectStreamWriter;
41  friend class JsonArrayStreamWriter;
42  std::ostringstream stream;
43  bool first;
44 
45  template <typename T>
47  {
48  stream << value;
49  return *this;
50  }
51 
53  {
54  if(first)
55  {
56  first = false;
57  }
58  else
59  {
60  stream << ',';
61  }
62  return *this;
63  }
64 
65  virtual std::ostream& finish() = 0;
66 
67  // Escape strings accordingly to the JSON standard
68  std::string escapeJsonString(const std::string& input);
69 };
70 
71 // Write a boolean to the stream.
72 template <>
73 JsonStreamWriter& JsonStreamWriter::operator<<(bool value);
74 // Write a string to the stream.
75 template <>
76 JsonStreamWriter& JsonStreamWriter::operator<<(const char* string);
77 // Write null (empty value) to the stream.
78 template <>
79 JsonStreamWriter& JsonStreamWriter::operator<<(JsonNull);
80 
81 /**
82  * @brief Write an object to a stream.
83  */
85 {
86 public:
87  JsonObjectStreamWriter() { stream << '{'; }
88 
89  template <typename T>
90  JsonObjectStreamWriter& operator<<(const std::pair<const char*, T> pair)
91  {
92  addSep() << pair.first << ':' << pair.second;
93  return *this;
94  }
95 
96 protected:
97  virtual std::ostream& finish() { return stream << '}'; }
98 };
99 
100 template <>
101 JsonObjectStreamWriter& JsonObjectStreamWriter::operator<<(const std::pair<const char*, const char*> pair);
102 
103 /**
104  * @brief Write an array to a stream.
105  */
107 {
108 public:
109  JsonArrayStreamWriter() { stream << '['; }
110 
111  template <typename T>
113  {
114  addSep() << value;
115  return *this;
116  }
117 
118 protected:
119  virtual std::ostream& finish() { return stream << ']'; }
120 };
121 }
122 }
123 
124 #endif
JsonArrayStreamWriter & operator<<(T value)
Definition: JsonWriter.hpp:112
Write an array to a stream.
Definition: JsonWriter.hpp:106
To manage 'null' element in JSON.
Definition: JsonWriter.hpp:17
Based class to write element to a stream.
Definition: JsonWriter.hpp:24
JsonStreamWriter & operator<<(T value)
Definition: JsonWriter.hpp:46
Write an object to a stream.
Definition: JsonWriter.hpp:84