1 // Copyright (c) 2006-2008 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 5 #ifndef BASE_JSON_JSON_WRITER_H_ 6 #define BASE_JSON_JSON_WRITER_H_ 7 8 #include <string> 9 10 #include "base/basictypes.h" 11 12 class Value; 13 14 namespace base { 15 16 class JSONWriter { 17 public: 18 // Given a root node, generates a JSON string and puts it into |json|. 19 // If |pretty_print| is true, return a slightly nicer formated json string 20 // (pads with whitespace to help readability). If |pretty_print| is false, 21 // we try to generate as compact a string as possible. 22 // TODO(tc): Should we generate json if it would be invalid json (e.g., 23 // |node| is not a DictionaryValue/ListValue or if there are inf/-inf float 24 // values)? 25 static void Write(const Value* const node, bool pretty_print, 26 std::string* json); 27 28 // Same as above, but has an option to not escape the string, preserving its 29 // UTF8 characters. It is useful if you can pass resulting string to the 30 // JSON parser in binary form (as UTF8). 31 static void WriteWithOptionalEscape(const Value* const node, 32 bool pretty_print, 33 bool escape, 34 std::string* json); 35 36 // A static, constant JSON string representing an empty array. Useful 37 // for empty JSON argument passing. 38 static const char* kEmptyArray; 39 40 private: 41 JSONWriter(bool pretty_print, std::string* json); 42 43 // Called recursively to build the JSON string. Whe completed, value is 44 // json_string_ will contain the JSON. 45 void BuildJSONString(const Value* const node, int depth, bool escape); 46 47 // Appends a quoted, escaped, version of str to json_string_. 48 void AppendQuotedString(const std::wstring& str); 49 50 // Adds space to json_string_ for the indent level. 51 void IndentLine(int depth); 52 53 // Where we write JSON data as we generate it. 54 std::string* json_string_; 55 56 bool pretty_print_; 57 58 DISALLOW_COPY_AND_ASSIGN(JSONWriter); 59 }; 60 61 } // namespace base 62 63 #endif // BASE_JSON_JSON_WRITER_H_ 64