• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "base/json/json_string_value_serializer.h"
6 
7 #include "base/json/json_reader.h"
8 #include "base/json/json_writer.h"
9 #include "base/logging.h"
10 
11 using base::Value;
12 
JSONStringValueSerializer(std::string * json_string)13 JSONStringValueSerializer::JSONStringValueSerializer(std::string* json_string)
14     : json_string_(json_string),
15       pretty_print_(false) {
16 }
17 
~JSONStringValueSerializer()18 JSONStringValueSerializer::~JSONStringValueSerializer() {}
19 
Serialize(const Value & root)20 bool JSONStringValueSerializer::Serialize(const Value& root) {
21   return SerializeInternal(root, false);
22 }
23 
SerializeAndOmitBinaryValues(const Value & root)24 bool JSONStringValueSerializer::SerializeAndOmitBinaryValues(
25     const Value& root) {
26   return SerializeInternal(root, true);
27 }
28 
SerializeInternal(const Value & root,bool omit_binary_values)29 bool JSONStringValueSerializer::SerializeInternal(const Value& root,
30                                                   bool omit_binary_values) {
31   if (!json_string_)
32     return false;
33 
34   int options = 0;
35   if (omit_binary_values)
36     options |= base::JSONWriter::OPTIONS_OMIT_BINARY_VALUES;
37   if (pretty_print_)
38     options |= base::JSONWriter::OPTIONS_PRETTY_PRINT;
39 
40   return base::JSONWriter::WriteWithOptions(root, options, json_string_);
41 }
42 
JSONStringValueDeserializer(const base::StringPiece & json_string)43 JSONStringValueDeserializer::JSONStringValueDeserializer(
44     const base::StringPiece& json_string)
45     : json_string_(json_string),
46       allow_trailing_comma_(false) {
47 }
48 
~JSONStringValueDeserializer()49 JSONStringValueDeserializer::~JSONStringValueDeserializer() {}
50 
Deserialize(int * error_code,std::string * error_str)51 std::unique_ptr<Value> JSONStringValueDeserializer::Deserialize(
52     int* error_code,
53     std::string* error_str) {
54   return base::JSONReader::ReadAndReturnError(
55       json_string_, allow_trailing_comma_ ? base::JSON_ALLOW_TRAILING_COMMAS
56                                           : base::JSON_PARSE_RFC,
57       error_code, error_str);
58 }
59