• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 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 "util/json/json_serialization.h"
6 
7 #include <memory>
8 #include <sstream>
9 #include <string>
10 #include <utility>
11 
12 #include "json/reader.h"
13 #include "json/writer.h"
14 #include "platform/base/error.h"
15 #include "util/osp_logging.h"
16 
17 namespace openscreen {
18 namespace json {
19 
Parse(absl::string_view document)20 ErrorOr<Json::Value> Parse(absl::string_view document) {
21   Json::CharReaderBuilder builder;
22   Json::CharReaderBuilder::strictMode(&builder.settings_);
23   if (document.empty()) {
24     return ErrorOr<Json::Value>(Error::Code::kJsonParseError, "empty document");
25   }
26 
27   Json::Value root_node;
28   std::string error_msg;
29   std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
30   const bool succeeded =
31       reader->parse(document.begin(), document.end(), &root_node, &error_msg);
32   if (!succeeded) {
33     return ErrorOr<Json::Value>(Error::Code::kJsonParseError, error_msg);
34   }
35 
36   return root_node;
37 }
38 
Stringify(const Json::Value & value)39 ErrorOr<std::string> Stringify(const Json::Value& value) {
40   if (value.empty()) {
41     return ErrorOr<std::string>(Error::Code::kJsonWriteError, "Empty value");
42   }
43 
44   Json::StreamWriterBuilder factory;
45 #ifndef _DEBUG
46   // Default is to "pretty print" the output JSON in a human readable
47   // format. On non-debug builds, we can remove pretty printing by simply
48   // getting rid of all indentation.
49   factory["indentation"] = "";
50 #endif
51 
52   std::unique_ptr<Json::StreamWriter> const writer(factory.newStreamWriter());
53   std::ostringstream stream;
54   writer->write(value, &stream);
55 
56   if (!stream) {
57     // Note: jsoncpp doesn't give us more information about what actually
58     // went wrong, just says to "check the stream". However, failures on
59     // the stream should be rare, as we do not throw any errors in the jsoncpp
60     // library.
61     return ErrorOr<std::string>(Error::Code::kJsonWriteError, "Invalid stream");
62   }
63 
64   return stream.str();
65 }
66 
67 }  // namespace json
68 }  // namespace openscreen
69