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 5 #ifndef BASE_JSON_JSON_WRITER_H_ 6 #define BASE_JSON_JSON_WRITER_H_ 7 8 #include <stddef.h> 9 10 #include <string> 11 12 #include "base/macros.h" 13 14 namespace base { 15 16 class Value; 17 18 class JSONWriter { 19 public: 20 enum Options { 21 // This option instructs the writer that if a Binary value is encountered, 22 // the value (and key if within a dictionary) will be omitted from the 23 // output, and success will be returned. Otherwise, if a binary value is 24 // encountered, failure will be returned. 25 OPTIONS_OMIT_BINARY_VALUES = 1 << 0, 26 27 // Return a slightly nicer formatted json string (pads with whitespace to 28 // help with readability). 29 OPTIONS_PRETTY_PRINT = 1 << 2, 30 }; 31 32 // Given a root node, generates a JSON string and puts it into |json|. 33 // The output string is overwritten and not appended. 34 // 35 // TODO(tc): Should we generate json if it would be invalid json (e.g., 36 // |node| is not a DictionaryValue/ListValue or if there are inf/-inf float 37 // values)? Return true on success and false on failure. 38 static bool Write(const Value& node, std::string* json); 39 40 // Same as above but with |options| which is a bunch of JSONWriter::Options 41 // bitwise ORed together. Return true on success and false on failure. 42 static bool WriteWithOptions(const Value& node, 43 int options, 44 std::string* json); 45 46 private: 47 JSONWriter(int options, std::string* json); 48 49 // Called recursively to build the JSON string. When completed, 50 // |json_string_| will contain the JSON. 51 bool BuildJSONString(const Value& node, size_t depth); 52 53 // Adds space to json_string_ for the indent level. 54 void IndentLine(size_t depth); 55 56 bool omit_binary_values_; 57 bool pretty_print_; 58 59 // Where we write JSON data as we generate it. 60 std::string* json_string_; 61 62 DISALLOW_COPY_AND_ASSIGN(JSONWriter); 63 }; 64 65 } // namespace base 66 67 #endif // BASE_JSON_JSON_WRITER_H_ 68