json_string_value_serializer.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. #include "base/json/json_string_value_serializer.h"
  5. #include "base/json/json_reader.h"
  6. #include "base/json/json_writer.h"
  7. using base::Value;
  8. JSONStringValueSerializer::JSONStringValueSerializer(std::string* json_string)
  9. : json_string_(json_string),
  10. pretty_print_(false) {
  11. }
  12. JSONStringValueSerializer::~JSONStringValueSerializer() = default;
  13. bool JSONStringValueSerializer::Serialize(base::ValueView root) {
  14. return SerializeInternal(root, false);
  15. }
  16. bool JSONStringValueSerializer::SerializeAndOmitBinaryValues(
  17. base::ValueView root) {
  18. return SerializeInternal(root, true);
  19. }
  20. bool JSONStringValueSerializer::SerializeInternal(base::ValueView root,
  21. bool omit_binary_values) {
  22. if (!json_string_)
  23. return false;
  24. int options = 0;
  25. if (omit_binary_values)
  26. options |= base::JSONWriter::OPTIONS_OMIT_BINARY_VALUES;
  27. if (pretty_print_)
  28. options |= base::JSONWriter::OPTIONS_PRETTY_PRINT;
  29. return base::JSONWriter::WriteWithOptions(root, options, json_string_);
  30. }
  31. JSONStringValueDeserializer::JSONStringValueDeserializer(
  32. const base::StringPiece& json_string,
  33. int options)
  34. : json_string_(json_string), options_(options) {}
  35. JSONStringValueDeserializer::~JSONStringValueDeserializer() = default;
  36. std::unique_ptr<Value> JSONStringValueDeserializer::Deserialize(
  37. int* error_code,
  38. std::string* error_str) {
  39. auto ret =
  40. base::JSONReader::ReadAndReturnValueWithError(json_string_, options_);
  41. if (ret.has_value())
  42. return base::Value::ToUniquePtrValue(std::move(*ret));
  43. if (error_code)
  44. *error_code = base::ValueDeserializer::kErrorCodeInvalidFormat;
  45. if (error_str)
  46. *error_str = std::move(ret.error().message);
  47. return nullptr;
  48. }