xref: /aosp_15_r20/external/cronet/base/json/json_string_value_serializer.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 <string_view>
8 
9 #include "base/json/json_reader.h"
10 #include "base/json/json_writer.h"
11 
12 using base::Value;
13 
JSONStringValueSerializer(std::string * json_string)14 JSONStringValueSerializer::JSONStringValueSerializer(std::string* json_string)
15     : json_string_(json_string),
16       pretty_print_(false) {
17 }
18 
19 JSONStringValueSerializer::~JSONStringValueSerializer() = default;
20 
Serialize(base::ValueView root)21 bool JSONStringValueSerializer::Serialize(base::ValueView root) {
22   return SerializeInternal(root, false);
23 }
24 
SerializeAndOmitBinaryValues(base::ValueView root)25 bool JSONStringValueSerializer::SerializeAndOmitBinaryValues(
26     base::ValueView root) {
27   return SerializeInternal(root, true);
28 }
29 
SerializeInternal(base::ValueView root,bool omit_binary_values)30 bool JSONStringValueSerializer::SerializeInternal(base::ValueView root,
31                                                   bool omit_binary_values) {
32   if (!json_string_)
33     return false;
34 
35   int options = 0;
36   if (omit_binary_values)
37     options |= base::JSONWriter::OPTIONS_OMIT_BINARY_VALUES;
38   if (pretty_print_)
39     options |= base::JSONWriter::OPTIONS_PRETTY_PRINT;
40 
41   return base::JSONWriter::WriteWithOptions(root, options, json_string_);
42 }
43 
JSONStringValueDeserializer(std::string_view json_string,int options)44 JSONStringValueDeserializer::JSONStringValueDeserializer(
45     std::string_view json_string,
46     int options)
47     : json_string_(json_string), options_(options) {}
48 
49 JSONStringValueDeserializer::~JSONStringValueDeserializer() = default;
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   auto ret =
55       base::JSONReader::ReadAndReturnValueWithError(json_string_, options_);
56   if (ret.has_value())
57     return base::Value::ToUniquePtrValue(std::move(*ret));
58 
59   if (error_code)
60     *error_code = base::ValueDeserializer::kErrorCodeInvalidFormat;
61   if (error_str)
62     *error_str = std::move(ret.error().message);
63   return nullptr;
64 }
65