Cinder  0.8.6
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
Json.h
Go to the documentation of this file.
1 /*
2  Copyright (c) 2012, The Cinder Project
3  All rights reserved.
4 
5  This code is designed for use with the Cinder C++ library, http://libcinder.org
6 
7  Redistribution and use in source and binary forms, with or without modification, are permitted provided that
8  the following conditions are met:
9 
10  * Redistributions of source code must retain the above copyright notice, this list of conditions and
11  the following disclaimer.
12  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
13  the following disclaimer in the documentation and/or other materials provided with the distribution.
14 
15  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
16  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
17  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
18  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
19  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
21  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
22  POSSIBILITY OF SUCH DAMAGE.
23 */
24 
25 #pragma once
26 
27 #include "cinder/DataSource.h"
28 #include "cinder/DataTarget.h"
29 #include "cinder/Exception.h"
30 #include "cinder/Utilities.h"
31 
32 #include <string>
33 #include <boost/container/list.hpp>
34 
35 namespace Json {
36  class Value;
37 }
38 
39 namespace cinder {
40 
41 class JsonTree {
42  public:
43 
45  typedef boost::container::list<JsonTree> Container;
46 
47  typedef Container::const_iterator ConstIter;
48  typedef Container::iterator Iter;
50 
53 
55  class ParseOptions {
56  public:
58  ParseOptions();
60  ParseOptions& ignoreErrors( bool ignore = true );
62  bool getIgnoreErrors() const;
63 
64  private:
66  bool mIgnoreErrors;
68 
69  };
70 
72  class WriteOptions {
73  public:
75  WriteOptions();
79  WriteOptions& indented( bool indent = true );
81  bool getCreateDocument() const;
83  bool getIndented() const;
84 
85  private:
87  bool mCreateDocument;
88  bool mIndented;
90 
91  };
92 
94 
96  explicit JsonTree();
98  JsonTree( const JsonTree &jsonTree );
101  explicit JsonTree( DataSourceRef dataSource, ParseOptions parseOptions = ParseOptions() );
103  explicit JsonTree( const std::string &jsonString, ParseOptions parseOptions = ParseOptions() );
105  explicit JsonTree( const std::string &key, bool value );
107  explicit JsonTree( const std::string &key, double value );
109  explicit JsonTree( const std::string &key, float value );
111  explicit JsonTree( const std::string &key, int value );
113  explicit JsonTree( const std::string &key, const std::string &value );
115  explicit JsonTree( const std::string &key, const char *value );
117  explicit JsonTree( const std::string &key, uint32_t value );
119  explicit JsonTree( const std::string &key, int64_t value );
121  explicit JsonTree( const std::string &key, uint64_t value );
122 
124  static JsonTree makeArray( const std::string &key = "" );
126  static JsonTree makeObject( const std::string &key = "" );
127 
129 
131  std::string serialize() const;
132 
134  Iter begin();
136  ConstIter begin() const;
138  Iter end();
140  ConstIter end() const;
141 
143  JsonTree& operator=( const JsonTree &jsonTree );
144 
147  JsonTree& operator[]( const std::string &relativePath );
150  const JsonTree& operator[]( const std::string &relativePath ) const;
152  JsonTree& operator[]( size_t index );
154  const JsonTree& operator[]( size_t index ) const;
156  friend std::ostream& operator<<( std::ostream &out, const JsonTree &json );
157 
160  JsonTree& getChild( const std::string &relativePath, bool caseSensitive = false, char separator = '.' );
163  const JsonTree& getChild( const std::string &relativePath, bool caseSensitive = false, char separator = '.' ) const;
165  JsonTree& getChild( size_t index );
167  const JsonTree& getChild( size_t index ) const;
169  const Container& getChildren() const;
171  size_t getNumChildren() const { return getChildren().size(); }
172 
175  bool hasChild( const std::string &relativePath, bool caseSensitive = false, char separator = '.' ) const;
177  bool hasChildren() const;
178 
180  JsonTree& getParent();
182  const JsonTree& getParent() const;
184  bool hasParent() const;
185 
187  void clear();
192  JsonTree& addChild( const JsonTree &newChild );
197  void pushBack( const JsonTree &newChild );
199  void removeChild( size_t index );
201  Iter removeChild( Iter pos );
203  void replaceChild( size_t index, const JsonTree &newChild );
205  void replaceChild( Iter pos, const JsonTree &newChild );
206 
210  void write( const fs::path &path, WriteOptions writeOptions = WriteOptions() );
214  void write( DataTargetRef target, WriteOptions writeOptions = WriteOptions() );
215 
217  const std::string& getKey() const;
218 
220  std::string getPath( char separator = '.' ) const;
221 
224  template <typename T>
225  inline T getValue() const
226  {
227  try {
228  return fromString<T>( mValue );
229  } catch ( boost::bad_lexical_cast &) {
230  throw ExcNonConvertible( * this );
231  }
232  return (T)0; // Unreachable. Prevents warning.
233  }
235  template <typename T>
236  inline T getValueForKey( const std::string &relativePath, bool caseSensitive = false, char separator = '.' ) const { return getChild( relativePath, caseSensitive, separator ).getValue<T>(); }
238  template <typename T>
239  inline T getValueAtIndex( size_t index ) const { return getChild( index ).getValue<T>(); }
240 
242  const std::string& getValue() const { return mValue; }
244  const inline std::string& getValueForKey( const std::string &relativePath, bool caseSensitive = false, char separator = '.' ) const { return getChild( relativePath, caseSensitive, separator ).getValue(); }
246  const inline std::string& getValueAtIndex( size_t index ) const { return getChild( index ).getValue(); }
247 
249  NodeType getNodeType() const { return mNodeType; }
250 
251 private:
252 
254  enum ValueType { VALUE_BOOL, VALUE_DOUBLE, VALUE_INT, VALUE_STRING, VALUE_UINT };
255 
256  explicit JsonTree( const std::string &key, const Json::Value &value );
257 
258  Json::Value createNativeDoc( WriteOptions writeOptions = WriteOptions() ) const;
259  static Json::Value deserializeNative( const std::string &jsonString, ParseOptions parseOptions );
260  static std::string serializeNative( const Json::Value &value );
261 
262  void init( const std::string &key, const Json::Value &value, bool setType = false,
263  NodeType nodeType = NODE_VALUE, ValueType valueType = VALUE_STRING );
264 
265  JsonTree* getNodePtr( const std::string &relativePath, bool caseSensitive, char separator ) const;
266  static bool isIndex( const std::string &key );
267 
268  Container mChildren;
269  std::string mKey;
270  JsonTree *mParent;
271  NodeType mNodeType;
272  std::string mValue;
273  ValueType mValueType;
275 
276  public:
277 
279 
281  class Exception : public cinder::Exception
282  {
283  };
284 
287  public:
288  ExcChildNotFound( const JsonTree &node, const std::string &key ) throw();
289  virtual const char* what() const throw()
290  {
291  return mMessage;
292  }
293 
294  private:
295  char mMessage[ 2048 ];
296  };
297 
300  public:
301  ExcNonConvertible( const JsonTree &node ) throw();
302  virtual const char* what() const throw()
303  {
304  return mMessage;
305  }
306 
307  private:
308  char mMessage[ 2048 ];
309  };
310 
313  public:
314  ExcJsonParserError( const std::string &errorMessage ) throw();
315  virtual const char* what() const throw()
316  {
317  return mMessage;
318  }
319 
320  private:
321  char mMessage[ 2048 ];
322  };
323 
324 };
325 
326 std::ostream& operator<<( std::ostream &out, const JsonTree &json );
327 
328 } // namespace cinder
WriteOptions & indented(bool indent=true)
Sets whether JSON string is indented. Default true.
Definition: Json.cpp:68
void replaceChild(size_t index, const JsonTree &newChild)
Replaces the child at index with JsonTree newChild. Throws ExcChildNotFound if none matches...
Definition: Json.cpp:334
WriteOptions()
Default options. Indents. Does not create root document.
Definition: Json.cpp:57
Options for JSON writing. Passed to the write method.
Definition: Json.h:72
bool hasChildren() const
Returns whether this node has a parent node.
Definition: Json.cpp:449
void write(const fs::path &path, WriteOptions writeOptions=WriteOptions())
Definition: Json.cpp:660
T getValueAtIndex(size_t index) const
Returns the value of the child at relativePath. Default type T is std::string. Convenience shortcut f...
Definition: Json.h:239
GLsizei const GLchar ** string
Definition: GLee.h:2427
bool getIgnoreErrors() const
Returns whether JSON parse errors are ignored.
Definition: Json.cpp:52
JsonTree & getChild(const std::string &relativePath, bool caseSensitive=false, char separator= '.')
Definition: Json.cpp:399
Iter end()
Returns an Iter which marks the end of the children of this node.
Definition: Json.cpp:389
Exception expressing the absence of an expected child node.
Definition: Json.h:286
T getValue() const
Returns the value of the node cast to T using ci::fromString(). float value = myNode.getValue( "key" );
Definition: Json.h:225
ExcChildNotFound(const JsonTree &node, const std::string &key)
Definition: Json.cpp:699
T getValueForKey(const std::string &relativePath, bool caseSensitive=false, char separator= '.') const
Returns the value of the child at relativePath. Default type T is std::string. Convenience shortcut f...
Definition: Json.h:236
GLuint index
Definition: GLee.h:2259
Iter begin()
Returns an Iter to the first child of this node.
Definition: Json.cpp:379
GLenum target
Definition: GLee.h:13607
const std::string & getValueAtIndex(size_t index) const
Returns the value of the child at relativePath. Default type T is std::string. Convenience shortcut f...
Definition: Json.h:246
void removeChild(size_t index)
Removes the child at index. Throws ExcChildNotFound if none matches.
Definition: Json.cpp:313
Exception expressing the existence of errors when serializing or deserializing JSON.
Definition: Json.h:312
ParseOptions & ignoreErrors(bool ignore=true)
Sets if JSON parse errors are ignored. Default true.
Definition: Json.cpp:46
Definition: Json.h:52
ParseOptions()
Default options. Enables parsing errors.
Definition: Json.cpp:41
bool getCreateDocument() const
whether JSON is wrapped in a 'document root' object.
Definition: Json.cpp:74
JsonTree & operator[](const std::string &relativePath)
Definition: Json.cpp:359
const std::string & getKey() const
Returns the node's key as a string. Returns index if node does not have a key.
Definition: Json.cpp:467
Definition: Json.h:52
const std::string & getValue() const
Returns the value of the node as a string.
Definition: Json.h:242
friend std::ostream & operator<<(std::ostream &out, const JsonTree &json)
Streams the JsonTree json to std::ostream out with standard formatting.
bool hasChild(const std::string &relativePath, bool caseSensitive=false, char separator= '.') const
Definition: Json.cpp:444
Definition: Json.h:52
virtual const char * what() const
Definition: Json.h:289
bool getIndented() const
Returns whether JSON string is indented.
Definition: Json.cpp:79
Definition: Json.h:41
Base class for JsonTree exceptions.
Definition: Json.h:281
virtual const char * what() const
Definition: Json.h:315
virtual const char * what() const
Definition: Json.h:302
size_t getNumChildren() const
Returns the number of child nodes.
Definition: Json.h:171
const Container & getChildren() const
Returns a reference to the node's list of children nodes.
Definition: Json.cpp:439
Definition: Json.h:52
void clear()
Removes all child nodes.
Definition: Json.cpp:289
JsonTree & operator=(const JsonTree &jsonTree)
Assigns the JsonTree a new value, and creates it if it doesn't exist.
Definition: Json.cpp:104
std::string serialize() const
Returns the JsonTree as a string with standard formatting.
Definition: Json.cpp:643
typedef int64_t(APIENTRYP GLEEPFNGLXSWAPBUFFERSMSCOMLPROC)(Display *dpy
Definition: Json.h:52
GLsizei const GLfloat * value
Definition: GLee.h:2487
WriteOptions & createDocument(bool createDocument=true)
Sets whether JSON is wrapped in a 'document root' object. Default false.
Definition: Json.cpp:62
std::ostream & operator<<(std::ostream &lhs, const ColorT< float > &rhs)
Definition: Color.cpp:203
Options for JSON parsing. Passed to the JsonTree constructor.
Definition: Json.h:55
JsonTree & getParent()
Returns a reference to the node which is the parent of this node.
Definition: Json.cpp:454
static JsonTree makeArray(const std::string &key="")
Definition: Json.cpp:190
JsonTree & addChild(const JsonTree &newChild)
Definition: Json.cpp:294
NodeType getNodeType() const
Returns the type of the node.
Definition: Json.h:249
std::shared_ptr< class DataTarget > DataTargetRef
Definition: DataTarget.h:33
bool hasParent() const
Returns whether this node has a parent node.
Definition: Json.cpp:462
std::string getPath(char separator= '.') const
Definition: Json.cpp:472
Definition: Exception.h:32
const std::string & getValueForKey(const std::string &relativePath, bool caseSensitive=false, char separator= '.') const
Returns the value of the child at relativePath. Default type T is std::string. Convenience shortcut f...
Definition: Json.h:244
NodeType
Enum listing all types of JSON nodes understood by the parser.
Definition: Json.h:52
std::shared_ptr< class DataSource > DataSourceRef
Definition: DataSource.h:35
static JsonTree makeObject(const std::string &key="")
Definition: Json.cpp:198
ExcJsonParserError(const std::string &errorMessage)
Definition: Json.cpp:717
Exception expressing the inability to convert a node's value to a requested type. ...
Definition: Json.h:299
JsonTree()
Creates a null JsonTree.
Definition: Json.cpp:86
void pushBack(const JsonTree &newChild)
Definition: Json.cpp:300
ExcNonConvertible(const JsonTree &node)
Definition: Json.cpp:708