本文整理汇总了Java中com.google.protobuf.util.JsonFormat类的典型用法代码示例。如果您正苦于以下问题:Java JsonFormat类的具体用法?Java JsonFormat怎么用?Java JsonFormat使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JsonFormat类属于com.google.protobuf.util包,在下文中一共展示了JsonFormat类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: upsertProduct
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Test
public void upsertProduct() throws Exception {
Product product = Product.newBuilder()
.setProductId(faker.number().randomNumber())
.setProductName(faker.company().name())
.setProductPrice(faker.number().randomDouble(2, 10, 100))
.setProductStatus(ProductStatus.InStock)
.build();
productDao.upsertProduct(product);
esClient.admin().indices().flush(Requests.flushRequest(INDEX)).actionGet();
GetResponse getResponse = esClient.prepareGet(INDEX, TYPE, String.valueOf(product.getProductId())).get();
JsonFormat.Parser jsonParser = injector.getInstance(JsonFormat.Parser.class);
Product.Builder builder = Product.newBuilder();
jsonParser.merge(getResponse.getSourceAsString(), builder);
assertThat(builder.build()).isEqualTo(product);
}
示例2: parseFeatures
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
/**
* 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);
try {
FeatureDatabase.Builder database = FeatureDatabase.newBuilder();
JsonFormat.parser().merge(reader, database);
return database.getFeatureList();
} finally {
reader.close();
}
} finally {
input.close();
}
}
示例3: getPredictRequestWithCustomDefaultFromJSON
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
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;
}
示例4: configure
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Override
protected void configure() {
bind(Configuration.class).toProvider(ConfigurationProvider.class).in(Singleton.class);
bind(TransportClient.class).toProvider(TransportClientProvider.class).in(Singleton.class);
bind(JsonFormat.Printer.class).toInstance(JsonFormat.printer());
bind(JsonFormat.Parser.class).toInstance(JsonFormat.parser());
}
示例5: testDatastoreToGcs_EntityToJson_noTransform
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Test
public void testDatastoreToGcs_EntityToJson_noTransform() throws Exception {
DoFnTester<Entity, String> fnTester = DoFnTester.of(EntityToJson.newBuilder()
.setJsTransformPath(StaticValueProvider.of(null))
.setJsTransformFunctionName(StaticValueProvider.of(null))
.build());
Builder entityBuilder = Entity.newBuilder();
JsonFormat.parser().usingTypeRegistry(
TypeRegistry.newBuilder()
.add(Entity.getDescriptor())
.build())
.merge(mEntityJson, entityBuilder);
Entity entity = entityBuilder.build();
List<String> entityJsonOutputs = fnTester.processBundle(entity);
Assert.assertEquals(mEntityJson, entityJsonOutputs.get(0));
}
示例6: testDatastoreToGcs_EntityToJson_withTransform
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Test
public void testDatastoreToGcs_EntityToJson_withTransform() throws Exception {
DoFnTester<Entity, String> fnTester = DoFnTester.of(EntityToJson.newBuilder()
.setJsTransformPath(StaticValueProvider.of(jsTransformPath))
.setJsTransformFunctionName(StaticValueProvider.of("transform"))
.build());
Builder entityBuilder = Entity.newBuilder();
JsonFormat.parser().usingTypeRegistry(
TypeRegistry.newBuilder()
.add(Entity.getDescriptor())
.build())
.merge(mEntityJson, entityBuilder);
Entity entity = entityBuilder.build();
List<String> entityJsonOutputs = fnTester.processBundle(entity);
Assert.assertEquals(mTransformedEntityJson, entityJsonOutputs.get(0));
}
示例7: testGcsToDatastore_EntityToJson_noTransform
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Test
public void testGcsToDatastore_EntityToJson_noTransform() throws Exception {
DoFnTester<String, Entity> fnTester = DoFnTester.of(JsonToEntity.newBuilder()
.setJsTransformPath(StaticValueProvider.of(null))
.setJsTransformFunctionName(StaticValueProvider.of(null))
.build());
List<Entity> output = fnTester.processBundle(mEntityJson);
Entity outputEntity = output.get(0);
Printer printer = JsonFormat.printer()
.omittingInsignificantWhitespace()
.usingTypeRegistry(
TypeRegistry.newBuilder()
.add(Entity.getDescriptor())
.build());
Assert.assertEquals(mEntityJson, printer.print(outputEntity));
}
示例8: testDatastoreToBq_EntityToTableRow_notransform
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Test
public void testDatastoreToBq_EntityToTableRow_notransform() throws Exception, IOException {
DoFnTester<Entity, TableRow> fnTester = DoFnTester.of(EntityToTableRow.newBuilder()
.setStrictCast(StaticValueProvider.of(true))
.setTableSchemaJson(StaticValueProvider.of(mTableSchemaJson))
.setJsTransformFunctionName(StaticValueProvider.of(null))
.setJsTransformPath(StaticValueProvider.of(null))
.build());
Builder entityBuilder = Entity.newBuilder();
JsonFormat.parser().usingTypeRegistry(
TypeRegistry.newBuilder()
.add(Entity.getDescriptor())
.build())
.merge(mEntityJson, entityBuilder);
Entity entity = entityBuilder.build();
List<TableRow> tableRows = fnTester.processBundle(entity);
TableRow tr = tableRows.get(0);
Assert.assertEquals(1, tableRows.size());
Assert.assertEquals("key(Drawing, '31ce830e-91d0-405e-855a-abe416cadc1f')", tr.get("__key__"));
Assert.assertEquals("79a1d9d9-e255-427a-9b09-f45157e97790", tr.get("canvasId"));
}
示例9: testToFeature
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Test
public void testToFeature() throws Exception {
Feature feature = Feature.newBuilder()
.setId("id1")
.setKey("key1")
.setGroup("app1")
.setDescription("desc1")
.setStatus(Status.off)
.build();
final String json = JsonFormat.printer().print(feature);
final Feature feature1 = FeatureSupport.toFeature(json);
assertEquals(feature.getId(), feature1.getId());
assertEquals(feature.getKey(), feature1.getKey());
assertEquals(feature.getGroup(), feature1.getGroup());
assertEquals(feature.getDescription(), feature1.getDescription());
assertEquals(feature.getStatus(), feature1.getStatus());
}
示例10: protobufToJsonWithDefaultValues
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
/**
* 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;
}
示例11: sendRawRequest
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
public synchronized ListenableFuture<Response> sendRawRequest(Request req) {
SettableListenableFuture<Response> slf = new SettableListenableFuture<Response>();
if(isConnected()) {
try {
if(log.isDebugEnabled()) {
log.debug("Sending Message:{}", JsonFormat.printer().omittingInsignificantWhitespace().print(req));
}
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
responseQueue.add(slf);
client.write(WebSocketFrameParser.makeWebSocketFrame(req.toByteArray().length, WebSocketOpCode.Binary.getValue(), false).getRawFrame());
client.write(ByteBuffer.wrap(req.toByteArray()));
return slf;
}
slf.setFailure(new IOException("Client is not connected!"));
return slf;
}
示例12: testFetchConfigWithWrongServiceName
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Test
public void testFetchConfigWithWrongServiceName() throws InvalidProtocolBufferException {
when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_NAME")).thenReturn(SERVICE_NAME);
when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_VERSION")).thenReturn(SERVICE_VERSION);
Service service = Service.newBuilder().setName("random-name").build();
String content = JsonFormat.printer().print(service);
testHttpTransport.addResponse(200, content);
try {
fetcher.get();
fail();
} catch (ServiceConfigException exception) {
assertEquals(
"Unexpected service name in service config: random-name", exception.getMessage());
}
}
示例13: testFetchConfigWithWrongServiceVersion
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@Test
public void testFetchConfigWithWrongServiceVersion() throws InvalidProtocolBufferException {
when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_NAME")).thenReturn(SERVICE_NAME);
when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_VERSION")).thenReturn(SERVICE_VERSION);
Service service = Service.newBuilder()
.setName(SERVICE_NAME)
.setId("random-version")
.build();
String content = JsonFormat.printer().print(service);
testHttpTransport.addResponse(200, content);
try {
fetcher.get();
fail();
} catch (ServiceConfigException exception) {
assertEquals(
"Unexpected service version in service config: random-version", exception.getMessage());
}
}
示例14: IndividualPokemonRepository
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
public IndividualPokemonRepository(String file) throws Exception {
String legacy = null;
if (!file.equals(POKEMONGO_JSON)) {
legacy = file.substring(0, 8);
}
final InputStream is = this.getClass().getResourceAsStream(file);
if (is == null) {
throw new IllegalArgumentException("Can not find " + file);
}
mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
printer = JsonFormat.printer().includingDefaultValueFields();
final RawData rawData = mapper.readValue(is, RawData.class);
all = createPokemons(rawData, legacy);
pokemonMap = all.getPokemonList().stream().collect(Collectors.toMap(p -> p.getPokemonId(), p -> p));
log.info("Loaded {} pokemons", all.getPokemonCount());
}
示例15: convertJsonToProto
import com.google.protobuf.util.JsonFormat; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public <T extends Message> T convertJsonToProto(T prototype, String json, String extensionName) {
try {
Builder builder = prototype.newBuilderForType();
JsonFormat.parser().merge(json, builder);
return (T) builder.build();
} catch (InvalidProtocolBufferException ex) {
diagCollector.addDiag(
Diag.error(
new SimpleLocation(extensionName),
"Extension %s cannot be converted into proto type %s. Details: %s",
extensionName,
prototype.getDescriptorForType().getFullName(),
ex.getMessage()));
return prototype;
}
}