public static <T extends Message> MethodDescriptor.Marshaller<T> jsonMarshaller(final T defaultInstance) { final JsonFormat.Printer printer = JsonFormat.printer().preservingProtoFieldNames(); final JsonFormat.Parser parser = JsonFormat.parser(); final Charset charset = Charset.forName("UTF-8");
/** * Converts a protobuf message to a JSON object * <p> * Note: Preserves the field names as defined in the proto definition * * @param input the protobuf message to convert * @return the converted JSON object */ public static JsonObject protobufToJson(Message input) { JsonObject object = new JsonObject(); if (input == null) { logger.warn("Protobuf message was null"); } else { try { String jsonString = JsonFormat.printer() .preservingProtoFieldNames() .print(input); object = new JsonParser().parse(jsonString).getAsJsonObject(); } catch (Exception e) { throw new RuntimeException("Error deserializing protobuf to json", e); } } return object; }
/** * Converts a protobuf message to a JSON object * <p> * Note: Preserves the field names as defined in the proto definition * Note: * * @param input the protobuf message to convert * @return the converted JSON object */ public static JsonObject protobufToJsonWithDefaultValues(Message input) { JsonObject object = new JsonObject(); if (input == null) { logger.warn("Protobuf message was null"); } else { try { String jsonString = JsonFormat.printer() .preservingProtoFieldNames() .includingDefaultValueFields() .print(input); object = new JsonParser().parse(jsonString).getAsJsonObject(); } catch (Exception e) { throw new RuntimeException("Error deserializing protobuf to json", e); } } return object; }
/** * Create a {@code Marshaller} for json protos of the same type as {@code defaultInstance}. * * <p>This is an unstable API and has not been optimized yet for performance. */ public static <T extends Message> Marshaller<T> jsonMarshaller(final T defaultInstance) { final Parser parser = JsonFormat.parser() .ignoringUnknownFields(); final Printer printer = JsonFormat.printer().preservingProtoFieldNames(); return jsonMarshaller(defaultInstance, parser, printer); }
private static Struct messageAsStruct(MessageOrBuilder message) { try { String json = JsonFormat.printer() .preservingProtoFieldNames() .print(message); Struct.Builder structBuilder = Struct.newBuilder(); JsonFormat.parser().merge(json, structBuilder); return structBuilder.build(); } catch (InvalidProtocolBufferException e) { throw new RuntimeException("Failed to convert protobuf message to struct", e); } }
private static void structAsMessage(Struct struct, Message.Builder messageBuilder) throws InvalidProtocolBufferException { String json = JsonFormat.printer() .preservingProtoFieldNames() .print(struct); JsonFormat.parser().merge(json, messageBuilder); }