下面列出了怎么用com.google.protobuf.util.JsonFormat的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Converts a protobuf message to a JSON object
* <p>
* Note: Camel-cases the field names as defined in the proto definition
*
* @param input the protobuf message to convert
* @return the converted JSON object
*/
public static JsonObject protobufToJsonCamelCase(Message input) {
JsonObject object = new JsonObject();
if (input == null) {
logger.warn("Protobuf message was null");
} else {
try {
String jsonString = JsonFormat.printer()
.print(input);
object = new JsonParser().parse(jsonString).getAsJsonObject();
} catch (Exception e) {
throw new RuntimeException("Error deserializing protobuf to json", e);
}
}
return object;
}
@RequestMapping(value = "/manager/list", method = RequestMethod.GET)
public void listManager(HttpServletRequest request, HttpServletResponse response)
throws InvalidProtocolBufferException {
// Create a blocking stub with the channel
ManagerServiceGrpc.ManagerServiceBlockingStub stub =
ManagerServiceGrpc.newBlockingStub(channel);
// Create a request
ManagerRequest listManagerRequest = ManagerRequest.newBuilder().build();
// Send the request using the stub
System.out.println("Client sending request");
ManagerResponse managerResponse = stub.listManager(listManagerRequest);
if (managerResponse.getStatusId() == 0) {
String data = JsonFormat.printer().preservingProtoFieldNames().print(managerResponse);
HttpUtils.setJsonBody(response, new ResponseInfo(0, "显示所有", data));
} else {
System.out.println("nothing");
HttpUtils.setJsonBody(response, new ResponseInfo(1, "无内容"));
}
}
private JobDescriptor loadTemplate(CommandContext context) throws IOException {
File templateFile = new File(context.getCLI().getOptionValue('f'));
System.out.println("Submitting job from file " + templateFile);
JobDescriptor.Builder builder = JobDescriptor.newBuilder();
try (FileReader fr = new FileReader(templateFile)) {
JsonFormat.parser().merge(fr, builder);
}
JobDescriptor applicajobDescriptorionInfo = builder.build();
if (context.getCLI().hasOption('d')) {
System.out.println(JsonFormat.printer().print(applicajobDescriptorionInfo));
}
return applicajobDescriptorionInfo;
}
@Test
public void writeJsonWithGoogleProtobuf() throws IOException {
this.converter = new ProtobufHttpMessageConverter(
new ProtobufHttpMessageConverter.ProtobufJavaUtilSupport(null, null),
this.extensionRegistry);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
MediaType contentType = MediaType.APPLICATION_JSON;
this.converter.write(this.testMsg, contentType, outputMessage);
assertEquals(contentType, outputMessage.getHeaders().getContentType());
final String body = outputMessage.getBodyAsString(Charset.forName("UTF-8"));
assertFalse("body is empty", body.isEmpty());
Msg.Builder builder = Msg.newBuilder();
JsonFormat.parser().merge(body, builder);
assertEquals(this.testMsg, builder.build());
assertNull(outputMessage.getHeaders().getFirst(
ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER));
assertNull(outputMessage.getHeaders().getFirst(
ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER));
}
public ClassificationReply getPredictReplyFromJson(String client,JsonNode json)
{
RPCConfig config = services.get(client);
try
{
TypeRegistry registry = null;
if (config != null && config.replyClass != null && json.has(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD))
{
if (!json.get(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD).has("@type"))
((ObjectNode) json.get(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD)).put("@type", "type.googleapis.com/" + config.replyClass.getName());
Method m = config.replyBuilder;
Message.Builder o = (Message.Builder) m.invoke(null);
registry = TypeRegistry.newBuilder().add(o.getDescriptorForType()).build();
}
ClassificationReply.Builder builder = ClassificationReply.newBuilder();
JsonFormat.Parser jFormatter = JsonFormat.parser();
if (registry != null)
jFormatter = jFormatter.usingTypeRegistry(registry);
jFormatter.merge(json.toString(), builder);
ClassificationReply reply = builder.build();
return reply;
} catch (Exception e) {
logger.error("Failed to convert json "+json.toString()+" to PredictReply",e);
return null;
}
}
@Test
void roundTrippingFamily() throws IOException {
Family original = TestExamples.rareDiseaseFamily();
String json = JsonFormat.printer().print(original);
String asYaml = FormatMapper.jsonToYaml(json);
System.out.println(asYaml);
System.out.println(json);
String asJson = FormatMapper.yamlToJson(asYaml);
System.out.println(asJson);
Family.Builder familyBuilder = Family.newBuilder();
JsonFormat.parser().merge(asJson, familyBuilder);
Family fromJson = familyBuilder.build();
//Ta-da!
assertThat(fromJson, equalTo(original));
}
private void writeDeviceSpecToFile(DeviceSpec deviceSpec, Path outputFile) {
try {
if (getOverwriteOutput()) {
Files.deleteIfExists(getOutputPath());
}
Path outputDirectory = getOutputPath().getParent();
if (outputDirectory != null && !Files.exists(outputDirectory)) {
logger.info("Output directory '" + outputDirectory + "' does not exist, creating it.");
Files.createDirectories(outputDirectory);
}
Files.write(outputFile, JsonFormat.printer().print(deviceSpec).getBytes(UTF_8));
} catch (IOException e) {
throw new UncheckedIOException(
String.format("Error while writing the output file '%s'.", outputFile), e);
}
}
private void removeInvalidWorkers(JedisCluster jedis, long testedAt, List<ShardWorker> workers) {
if (!workers.isEmpty()) {
for (ShardWorker worker : workers) {
String name = worker.getEndpoint();
String reason =
format("registration expired at %d, tested at %d", worker.getExpireAt(), testedAt);
WorkerChange workerChange =
WorkerChange.newBuilder()
.setEffectiveAt(toTimestamp(Instant.now()))
.setName(name)
.setRemove(
WorkerChange.Remove.newBuilder().setSource(source).setReason(reason).build())
.build();
try {
String workerChangeJson = JsonFormat.printer().print(workerChange);
removeWorkerAndPublish(jedis, name, workerChangeJson);
} catch (InvalidProtocolBufferException e) {
logger.log(Level.SEVERE, "error printing workerChange", e);
}
}
}
}
/**
* Parses the JSON input file containing the list of features.
*/
public static List<Feature> parseFeatures(URL file) throws IOException {
InputStream input = file.openStream();
try {
Reader reader = new InputStreamReader(input, Charset.forName("UTF-8"));
try {
FeatureDatabase.Builder database = FeatureDatabase.newBuilder();
JsonFormat.parser().merge(reader, database);
return database.getFeatureList();
} finally {
reader.close();
}
} finally {
input.close();
}
}
private ClassificationRequest getPredictRequestWithCustomDefaultFromJSON(JsonNode json) throws InvalidProtocolBufferException
{
ObjectMapper mapper = new ObjectMapper();
ObjectNode data = mapper.createObjectNode();
data.put("@type", "type.googleapis.com/" + DefaultCustomPredictRequest.class.getName());
data.put("values", json.get(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD));
((ObjectNode) json).put(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD, data);
Message.Builder o = DefaultCustomPredictRequest.newBuilder();
TypeRegistry registry = TypeRegistry.newBuilder().add(o.getDescriptorForType()).build();
ClassificationRequest.Builder builder = ClassificationRequest.newBuilder();
JsonFormat.Parser jFormatter = JsonFormat.parser();
if (registry != null)
jFormatter = jFormatter.usingTypeRegistry(registry);
jFormatter.merge(json.toString(), builder);
ClassificationRequest request = builder.build();
return request;
}
@Override
public boolean pollOperation(QueueEntry queueEntry, ExecutionStage.Value stage, long requeueAt)
throws IOException {
String operationName = queueEntry.getExecuteEntry().getOperationName();
DispatchedOperation o =
DispatchedOperation.newBuilder().setQueueEntry(queueEntry).setRequeueAt(requeueAt).build();
String json;
try {
json = JsonFormat.printer().print(o);
} catch (InvalidProtocolBufferException e) {
logger.log(Level.SEVERE, "error printing dispatched operation " + operationName, e);
return false;
}
return client.call(
jedis -> {
if (jedis.hexists(config.getDispatchedOperationsHashName(), operationName)) {
if (jedis.hset(config.getDispatchedOperationsHashName(), operationName, json) == 0) {
return true;
}
/* someone else beat us to the punch, delete our incorrectly added key */
jedis.hdel(config.getDispatchedOperationsHashName(), operationName);
}
return false;
});
}
@Test
void testEvidence() throws Exception {
OntologyClass publishedClinicalStudy = OntologyClass.
newBuilder().
setId("ECO:0006017").
setLabel("author statement from published clinical study used in manual assertion").
build();
ExternalReference reference = ExternalReference.newBuilder().
setId("PMID:20375004").
setDescription("Mutations in fibrillin-1 cause congenital scleroderma: stiff skin syndrome").
build();
Evidence evidence = Evidence.newBuilder().
setEvidenceCode(publishedClinicalStudy).
setReference(reference).
build();
System.out.println(JsonFormat.printer().includingDefaultValueFields().print(evidence));
}
@Test
void homozygousVariant() throws Exception {
Variant hom = Variant.newBuilder()
.setVcfAllele(FGFR2_PATH_ALLELE_1)
.setZygosity(HOM)
.build();
Phenopacket phenopacket = Phenopacket.newBuilder()
.setId("pfeiffer_homozygous_case")
.addVariants(hom)
.addDiseases(PFIEFFER_SYNDROME)
.setMetaData(META_DATA)
.build();
System.out.println(JsonFormat.printer().print(phenopacket));
}
public CreatePullRequestResponse createPullRequest(CreatePullRequestRequest request) {
try {
String requestData = JsonFormat.printer().print(request.getRequestData());
String response =
doRequest(
RequestMethod.POST,
String.format(CREATE_PULL_REQUEST, request.getOwner(), request.getRepo()),
requestData);
CreatePullRequestResponse.Builder builder = CreatePullRequestResponse.newBuilder();
JsonFormat.parser()
.ignoringUnknownFields()
.merge(String.format("{\"pull_request\":%s}", response), builder);
return builder.build();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public PullRequestCommentsResponse getPullRequestComments(PullRequestCommentsRequest request)
throws IOException {
PullRequestCommentsResponse.Builder builder = PullRequestCommentsResponse.newBuilder();
String response =
doRequest(
RequestMethod.GET,
String.format(
GET_COMMENTS_ON_PULL_REQUEST,
request.getOwner(),
request.getRepo(),
request.getNumber()));
JsonFormat.parser()
.ignoringUnknownFields()
.merge(String.format("{\"review_comment\":%s}", response), builder);
return builder.build();
}
public CreateIssueCommentResponse createIssueComment(CreateIssueCommentRequest request) {
try {
String requestData = JsonFormat.printer().print(request.getRequestData());
String response =
doRequest(
RequestMethod.POST,
String.format(
CREATE_COMMENT_ON_ISSUE,
request.getOwner(),
request.getRepo(),
request.getNumber()),
requestData);
CreateIssueCommentResponse.Builder builder = CreateIssueCommentResponse.newBuilder();
JsonFormat.parser()
.ignoringUnknownFields()
.merge(String.format("{\"issue_comment\":%s}", response), builder);
return builder.build();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@RequestMapping(value = "/power/list",method = RequestMethod.GET)
public void listPower(HttpServletRequest request, HttpServletResponse response) throws InvalidProtocolBufferException, InvalidProtocolBufferException {
// Create a blocking stub with the channel
PowerServiceGrpc.PowerServiceBlockingStub stub =
PowerServiceGrpc.newBlockingStub(channel);
// Create a request
PowerRequest listPowerRequest = PowerRequest.newBuilder().build();
// Send the request using the stub
System.out.println("Client sending request");
PowerResponse powerResponse = stub.listPower(listPowerRequest);
if(powerResponse.getStatusId()==0){
String data= JsonFormat.printer().includingDefaultValueFields().preservingProtoFieldNames().print(powerResponse);
HttpUtils.setJsonBody(response,new ResponseInfo(0,"显示所有用户",data));
}else
{
System.out.println("nothing");
HttpUtils.setJsonBody(response,new ResponseInfo(1,"无内容"));
}
}
@Override
public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
NotificationMessage.Builder notificationMessageBuilder = NotificationMessage.newBuilder();
try {
String jsonString = message.getData().toStringUtf8();
JsonFormat.parser().merge(jsonString, notificationMessageBuilder);
NotificationMessage notificationMessage = notificationMessageBuilder.build();
System.out.println(
String.format("Config id: %s", notificationMessage.getNotificationConfigName()));
System.out.println(String.format("Finding: %s", notificationMessage.getFinding()));
} catch (InvalidProtocolBufferException e) {
System.out.println("Could not parse message: " + e);
} finally {
consumer.ack();
}
}
protected static String formatRequestMetadataToJson(
OperationRequestMetadata operationRequestMetadata) throws InvalidProtocolBufferException {
JsonFormat.TypeRegistry typeRegistry =
JsonFormat.TypeRegistry.newBuilder()
.add(ExecuteResponse.getDescriptor())
.add(ExecuteOperationMetadata.getDescriptor())
.add(PreconditionFailure.getDescriptor())
.build();
String formattedRequestMetadata =
JsonFormat.printer()
.usingTypeRegistry(typeRegistry)
.omittingInsignificantWhitespace()
.print(operationRequestMetadata);
logger.log(Level.FINE, "{}", formattedRequestMetadata);
return formattedRequestMetadata;
}
@Override
public Optional<Job> get(String id) {
Job job = null;
try {
String json = new String(syncCommand.get(id.getBytes()));
if (json.isEmpty()) {
return Optional.empty();
}
Builder builder = Job.newBuilder();
JsonFormat.parser().merge(json, builder);
job = builder.build();
} catch (Exception e) {
log.error(String.format("Failed to parse JSON for Feast job: %s", e.getMessage()));
}
return Optional.ofNullable(job);
}
@Test
@Theory
public void checkFlagsConstructionWithDeviceSpec(
@FromDataPoints("deviceSpecs") String deviceSpecPath) throws Exception {
DeviceSpec.Builder expectedDeviceSpecBuilder = DeviceSpec.newBuilder();
try (Reader reader = TestData.openReader(deviceSpecPath)) {
JsonFormat.parser().merge(reader, expectedDeviceSpecBuilder);
}
DeviceSpec expectedDeviceSpec = expectedDeviceSpecBuilder.build();
BuildApksResult tableOfContentsProto = BuildApksResult.getDefaultInstance();
Path apksArchiveFile =
createApksArchiveFile(tableOfContentsProto, tmpDir.resolve("bundle.apks"));
Path deviceSpecFile = copyToTempDir(deviceSpecPath);
GetSizeCommand command =
GetSizeCommand.fromFlags(
new FlagParser()
.parse(
"get-size",
"total",
"--device-spec=" + deviceSpecFile,
"--apks=" + apksArchiveFile));
assertThat(command.getDeviceSpec()).isEqualTo(expectedDeviceSpec);
}
private ImportOptions getPipelineOptions(
String jobName, SourceProto.Source source, Set<StoreProto.Store> sinks)
throws IOException, IllegalAccessException {
ImportOptions pipelineOptions =
PipelineOptionsFactory.fromArgs(defaultOptions.toArgs()).as(ImportOptions.class);
JsonFormat.Printer printer = JsonFormat.printer();
pipelineOptions.setSpecsStreamingUpdateConfigJson(printer.print(specsStreamingUpdateConfig));
pipelineOptions.setSourceJson(printer.print(source));
pipelineOptions.setJobName(jobName);
pipelineOptions.setStoresJson(
sinks.stream().map(wrapException(printer::print)).collect(Collectors.toList()));
pipelineOptions.setRunner(DirectRunner.class);
pipelineOptions.setDefaultFeastProject(Project.DEFAULT_NAME);
pipelineOptions.setProject(""); // set to default value to satisfy validation
if (metrics.isEnabled()) {
pipelineOptions.setMetricsExporterType(metrics.getType());
if (metrics.getType().equals("statsd")) {
pipelineOptions.setStatsdHost(metrics.getHost());
pipelineOptions.setStatsdPort(metrics.getPort());
}
}
pipelineOptions.setBlockOnRun(false);
return pipelineOptions;
}
@Test
void compoundHeterozygousVariant() throws Exception {
Variant het1 = Variant.newBuilder()
.setVcfAllele(FGFR2_PATH_ALLELE_1)
.setZygosity(HET)
.build();
Variant het2 = Variant.newBuilder()
.setVcfAllele(FGFR2_LIKELY_PATH_ALLELE_2)
.setZygosity(HET)
.build();
Phenopacket phenopacket = Phenopacket.newBuilder()
.setId("pfeiffer_compound_heterozygous_case")
.addVariants(het1)
.addVariants(het2)
.addDiseases(PFIEFFER_SYNDROME)
.setMetaData(META_DATA)
.build();
System.out.println(JsonFormat.printer().print(phenopacket));
}
public static String toJson(Message msg) throws InvalidProtocolBufferException {
JsonFormat.Printer printer = JsonFormat.printer()
.omittingInsignificantWhitespace()
.usingTypeRegistry(JsonFormat.TypeRegistry.newBuilder()
.add(msg.getDescriptorForType())
.build());
return printer.print(msg);
}
public static <T> T fromJson(Message.Builder builder, String json, boolean ignoreUnknownFields) throws InvalidProtocolBufferException {
JsonFormat.Parser parser = JsonFormat.parser();
if (ignoreUnknownFields) {
parser = parser.ignoringUnknownFields();
}
parser.merge(json, builder);
//noinspection unchecked
return (T) builder.build();
}
@Override
public Object getValue() {
try {
return JsonFormat.printer()
.omittingInsignificantWhitespace()
.print((DynamicMessage) fieldValue);
} catch (InvalidProtocolBufferException e) {
return "";
}
}
private JsonNode getJSONFromMethod(Method m,Message msg,String fieldname) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, JsonParseException, IOException
{
Message.Builder o2 = (Message.Builder) m.invoke(null);
TypeRegistry registry = TypeRegistry.newBuilder().add(o2.getDescriptorForType()).build();
JsonFormat.Printer jPrinter = JsonFormat.printer();
String result = jPrinter.usingTypeRegistry(registry).print(msg);
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(result);
JsonNode jNode = mapper.readTree(parser);
if (jNode.has(fieldname) && jNode.get(fieldname).has("@type"))
((ObjectNode) jNode.get(fieldname)).remove("@type");
return jNode;
}
@Override
public void serialize(
Optional<Message> message, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
if (message.isPresent()) {
try {
gen.writeString(JsonFormat.printer().print(message.get()));
// Lets add this so we don't get unnecessary errors trying to print logs
} catch (IOException e) {
gen.writeString("Unexpected error trying to serialize proto object");
}
} else {
gen.writeString("No message");
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private ProtobufHttpMessageConverter newCustomProtobufMessageConverter() throws Exception {
Constructor[] constructors = ProtobufHttpMessageConverter.class.getDeclaredConstructors();
Constructor requiredConstructor = null;
for (Constructor constructor : constructors) {
if (constructor.getParameterTypes().length == 2) {
constructor.setAccessible(true);
requiredConstructor = constructor;
break;
}
}
Class[] classes = ProtobufHttpMessageConverter.class.getDeclaredClasses();
Class requiredClass = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().equals("ProtobufJavaUtilSupport")) {
requiredClass = clazz;
break;
}
}
Constructor pbUtilSupportConstructor = requiredClass.getConstructor(Parser.class, Printer.class);
pbUtilSupportConstructor.setAccessible(true);
Parser parser = JsonFormat.parser().ignoringUnknownFields();
Printer printer = JsonFormat.printer().includingDefaultValueFields().preservingProtoFieldNames()
.omittingInsignificantWhitespace();
Object support = pbUtilSupportConstructor.newInstance(parser, printer);
return (ProtobufHttpMessageConverter) requiredConstructor.newInstance(support, null);
}
private void writeGenesisBlock() throws IOException {
String json = JsonFormat.printer().print(genesisBlock);
writeToFile(
GenesisBlockBuilder.defaultGenesisBlockName,
json
);
}