下面列出了com.google.protobuf.util.JsonFormat#Parser ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
}
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;
}
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();
}
@VisibleForTesting
MessageReader(
JsonFormat.Parser jsonParser,
Descriptor descriptor,
BufferedReader bufferedReader,
String source) {
this.jsonParser = jsonParser;
this.descriptor = descriptor;
this.bufferedReader = bufferedReader;
this.source = source;
}
Reader(JsonFormat.Parser jsonParser,
Descriptors.Descriptor descriptor,
List<Map<String, Object>> payloadList) {
this.jsonParser = jsonParser;
this.descriptor = descriptor;
this.payloadList = payloadList;
}
@Test
public void testParseFromJSON() throws InvalidProtocolBufferException
{
String json = "{\"meta\":{\"modelName\":\"some-name\"},\"custom\":{\"@type\":\"type.googleapis.com/io.seldon.api.rpc.example.CustomPredictReply\",\"data\":\"some custom data\"}}";
ClassificationReply.Builder builder = ClassificationReply.newBuilder();
CustomPredictReply.Builder customBuilder = CustomPredictReply.newBuilder();
TypeRegistry registry = TypeRegistry.newBuilder().add(customBuilder.getDescriptorForType()).build();
JsonFormat.Parser jFormatter = JsonFormat.parser().usingTypeRegistry(registry);
jFormatter.merge(json, builder);
ClassificationReply reply = builder.build();
System.out.println(reply);
}
@Test
public void testParseFromJSONDefault() throws InvalidProtocolBufferException
{
String json = "{\"data\":{\"@type\":\"type.googleapis.com/io.seldon.api.rpc.DefaultCustomPredictRequest\",\"values\":[1.2,2.1]}}";
ClassificationRequest.Builder builder = ClassificationRequest.newBuilder();
DefaultCustomPredictRequest.Builder customBuilder = DefaultCustomPredictRequest.newBuilder();
TypeRegistry registry = TypeRegistry.newBuilder().add(customBuilder.getDescriptorForType()).build();
JsonFormat.Parser jFormatter = JsonFormat.parser().usingTypeRegistry(registry);
jFormatter.merge(json, builder);
ClassificationRequest request = builder.build();
System.out.println(request);
}
@Test
public void testCreatesFileAndWritesProtoJsonFormat() throws Exception {
File output = tmp.newFile();
BufferedOutputStream outputStream =
new BufferedOutputStream(Files.newOutputStream(Paths.get(output.getAbsolutePath())));
BuildEventStreamProtos.BuildEvent started =
BuildEventStreamProtos.BuildEvent.newBuilder()
.setStarted(BuildStarted.newBuilder().setCommand("build"))
.build();
when(buildEvent.asStreamProto(ArgumentMatchers.<BuildEventContext>any())).thenReturn(started);
JsonFormatFileTransport transport =
new JsonFormatFileTransport(
outputStream,
defaultOpts,
new LocalFilesArtifactUploader(),
artifactGroupNamer);
transport.sendBuildEvent(buildEvent);
transport.close().get();
try (Reader reader = new InputStreamReader(new FileInputStream(output))) {
JsonFormat.Parser parser = JsonFormat.parser();
BuildEventStreamProtos.BuildEvent.Builder builder =
BuildEventStreamProtos.BuildEvent.newBuilder();
parser.merge(reader, builder);
assertThat(builder.build()).isEqualTo(started);
}
}
public ProtobufJavaUtilSupport(@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this.parser = (parser != null ? parser : JsonFormat.parser());
this.printer = (printer != null ? printer : JsonFormat.printer());
}
public ProtobufJavaUtilSupport(@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this.parser = (parser != null ? parser : JsonFormat.parser());
this.printer = (printer != null ? printer : JsonFormat.printer());
}
@Override
protected JSONObject processRequest(JSONRPC2Request req, MessageContext ctx)
throws Exception
{
Map<String, Object> params = req.getNamedParams();
JSONObject wallet_data = (JSONObject) params.get("wallet");
WalletDatabase.Builder wallet_import = WalletDatabase.newBuilder();
JsonFormat.Parser parser = JsonFormat.parser();
parser.merge(wallet_data.toString(), wallet_import);
WalletDatabase new_db = wallet_import.build();
List<AddressSpecHash> addresses = WalletUtil.testWallet( new_db );
if (client.getConfig().getBoolean("watch_only") && (new_db.getKeysCount() > 0))
{
throw new ValidationException("Attempting to import wallet with keys into watch only wallet. Nope.");
}
client.getPurse().mergeIn( new_db );
JSONObject reply = new JSONObject();
JSONArray address_list = new JSONArray();
for(AddressSpecHash spec_hash : addresses)
{
String address = spec_hash.toAddressString( client.getParams() );
address_list.add(address);
}
reply.put("addresses", address_list);
JSONArray keypair_list = new JSONArray();
for(WalletKeyPair pair : new_db.getKeysList())
{
String key_string = HexUtil.getHexString( pair.getPublicKey() );
keypair_list.add(key_string);
}
reply.put("keys", keypair_list);
return reply;
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also
* accepting an initializer that allows the registration of message extensions.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
* @param registryInitializer an initializer for message extensions
* @deprecated as of 5.1, in favor of
* {@link #ProtobufJsonFormatHttpMessageConverter(JsonFormat.Parser, JsonFormat.Printer, ExtensionRegistry)}
*/
@Deprecated
public ProtobufJsonFormatHttpMessageConverter(@Nullable JsonFormat.Parser parser,
@Nullable JsonFormat.Printer printer, @Nullable ExtensionRegistryInitializer registryInitializer) {
super(new ProtobufJavaUtilSupport(parser, printer), null);
if (registryInitializer != null) {
registryInitializer.initializeExtensionRegistry(this.extensionRegistry);
}
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also
* accepting an initializer that allows the registration of message extensions.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
* @param registryInitializer an initializer for message extensions
* @deprecated as of 5.1, in favor of
* {@link #ProtobufJsonFormatHttpMessageConverter(JsonFormat.Parser, JsonFormat.Printer, ExtensionRegistry)}
*/
@Deprecated
public ProtobufJsonFormatHttpMessageConverter(@Nullable JsonFormat.Parser parser,
@Nullable JsonFormat.Printer printer, @Nullable ExtensionRegistryInitializer registryInitializer) {
super(new ProtobufJavaUtilSupport(parser, printer), null);
if (registryInitializer != null) {
registryInitializer.initializeExtensionRegistry(this.extensionRegistry);
}
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
*/
public ProtobufJsonFormatHttpMessageConverter(
@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this(parser, printer, (ExtensionRegistry)null);
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also
* accepting a registry that specifies protocol message extensions.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
* @param extensionRegistry the registry to populate
* @since 5.1
*/
public ProtobufJsonFormatHttpMessageConverter(@Nullable JsonFormat.Parser parser,
@Nullable JsonFormat.Printer printer, @Nullable ExtensionRegistry extensionRegistry) {
super(new ProtobufJavaUtilSupport(parser, printer), extensionRegistry);
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
*/
public ProtobufJsonFormatHttpMessageConverter(
@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this(parser, printer, (ExtensionRegistry)null);
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also
* accepting a registry that specifies protocol message extensions.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
* @param extensionRegistry the registry to populate
* @since 5.1
*/
public ProtobufJsonFormatHttpMessageConverter(@Nullable JsonFormat.Parser parser,
@Nullable JsonFormat.Printer printer, @Nullable ExtensionRegistry extensionRegistry) {
super(new ProtobufJavaUtilSupport(parser, printer), extensionRegistry);
}
/**
* Extract data from a JSON String and use them to construct a Protocol Buffers Message.
* @param jsonReader A reader providing the JSON data to parse
* @param builder A Message builder to use to construct the resulting Message
* @return the constructed Message
* @throws InvalidProtocolBufferException Thrown in case of invalid Message data
*/
public static Message fromJSON(Reader jsonReader, Message.Builder builder) throws IOException {
JsonFormat.Parser parser = JsonFormat.parser();
parser.merge(jsonReader, builder);
return builder.build();
}