1 // Copyright 2012 The Chromium Authors
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
10 using base::Value;
11
JSONStringValueSerializer(std::string * json_string)12 JSONStringValueSerializer::JSONStringValueSerializer(std::string* json_string)
13 : json_string_(json_string),
14 pretty_print_(false) {
15 }
16
17 JSONStringValueSerializer::~JSONStringValueSerializer() = default;
18
Serialize(base::ValueView root)19 bool JSONStringValueSerializer::Serialize(base::ValueView root) {
20 return SerializeInternal(root, false);
21 }
22
SerializeAndOmitBinaryValues(base::ValueView root)23 bool JSONStringValueSerializer::SerializeAndOmitBinaryValues(
24 base::ValueView root) {
25 return SerializeInternal(root, true);
26 }
27
SerializeInternal(base::ValueView root,bool omit_binary_values)28 bool JSONStringValueSerializer::SerializeInternal(base::ValueView root,
29 bool omit_binary_values) {
30 if (!json_string_)
31 return false;
32
33 int options = 0;
34 if (omit_binary_values)
35 options |= base::JSONWriter::OPTIONS_OMIT_BINARY_VALUES;
36 if (pretty_print_)
37 options |= base::JSONWriter::OPTIONS_PRETTY_PRINT;
38
39 return base::JSONWriter::WriteWithOptions(root, options, json_string_);
40 }
41
JSONStringValueDeserializer(const base::StringPiece & json_string,int options)42 JSONStringValueDeserializer::JSONStringValueDeserializer(
43 const base::StringPiece& json_string,
44 int options)
45 : json_string_(json_string), options_(options) {}
46
47 JSONStringValueDeserializer::~JSONStringValueDeserializer() = default;
48
Deserialize(int * error_code,std::string * error_str)49 std::unique_ptr<Value> JSONStringValueDeserializer::Deserialize(
50 int* error_code,
51 std::string* error_str) {
52 auto ret =
53 base::JSONReader::ReadAndReturnValueWithError(json_string_, options_);
54 if (ret.has_value())
55 return base::Value::ToUniquePtrValue(std::move(*ret));
56
57 if (error_code)
58 *error_code = base::ValueDeserializer::kErrorCodeInvalidFormat;
59 if (error_str)
60 *error_str = std::move(ret.error().message);
61 return nullptr;
62 }
63