| 196 | } |
| 197 | |
| 198 | std::string Message::toJSON(const JSONPrintOptions& options, ExceptionTracker& exceptionTracker) { |
| 199 | if (_descriptor == nullptr) { |
| 200 | exceptionTracker.onError("Cannot convert to JSON without a descriptor"); |
| 201 | return ""; |
| 202 | } |
| 203 | |
| 204 | auto encoded = encode(options.alwaysPrintPrimitiveFields); |
| 205 | |
| 206 | JSONHelper jsonHelper(_descriptor, encoded.data(), encoded.size()); |
| 207 | |
| 208 | auto outputOptions = google::protobuf::util::JsonPrintOptions(); |
| 209 | outputOptions.add_whitespace = options.pretty; |
| 210 | outputOptions.always_print_fields_with_no_presence = options.alwaysPrintPrimitiveFields; |
| 211 | outputOptions.always_print_enums_as_ints = options.alwaysPrintEnumsAsInts; |
| 212 | |
| 213 | auto result = google::protobuf::util::BinaryToJsonStream( |
| 214 | jsonHelper.typeResolver, jsonHelper.typeUrl, &jsonHelper.inputStream, &jsonHelper.outputStream, outputOptions); |
| 215 | |
| 216 | if (!result.ok()) { |
| 217 | exceptionTracker.onError(result.message()); |
| 218 | return ""; |
| 219 | } |
| 220 | |
| 221 | return jsonHelper.output; |
| 222 | } |
| 223 | |
| 224 | bool Message::decodeFromJSON(std::string_view json, ExceptionTracker& exceptionTracker) { |
| 225 | if (_descriptor == nullptr) { |