An open API service indexing awesome lists of open source software.

https://github.com/kaelzhang/java-fastjson-protobuf

Spring `HttpMessageConverter` implementation with Alibaba FastJson and serializer/deserializer of Protobuf Messages.
https://github.com/kaelzhang/java-fastjson-protobuf

fastjson fastjson-android grpc java protobuf

Last synced: 12 months ago
JSON representation

Spring `HttpMessageConverter` implementation with Alibaba FastJson and serializer/deserializer of Protobuf Messages.

Awesome Lists containing this project

README

          

[![Build Status](https://travis-ci.org/kaelzhang/java-fastjson-protobuf.svg?branch=master)](https://travis-ci.org/kaelzhang/java-fastjson-protobuf)
[![Coverage](https://codecov.io/gh/kaelzhang/java-fastjson-protobuf/branch/master/graph/badge.svg)](https://codecov.io/gh/kaelzhang/java-fastjson-protobuf)
[![Maven Version](https://img.shields.io/maven-metadata/v/http/central.maven.org/maven2/ai/ost/fastjson-protobuf/maven-metadata.xml.svg)](https://github.com/kaelzhang/java-fastjson-protobuf)

# fastjson-protobuf

Spring `HttpMessageConverter` implementation with Alibaba FastJson and serializer/deserializer of Protobuf Messages.

With `fastjson-protobuf`, we can use protocol buffers to define both request and response entities.

Only **proto3** is supported for now.

## Install

### Gradle

```gradle
dependencies {
compile "ai.ost:fastjson-protobuf:${VERSION}"
}
```

### Maven

```xml

ai.ost
fastjson-protobuf
${VERSION}

```

## Usage

First, define our own `HttpMessageConverter`

```java
@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(
List> converters
) {

FastJsonProtobufHttpMessageConverter converter =
new FastJsonProtobufHttpMessageConverter();

converter.setSupportedMediaTypes(
Arrays.asList(
MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON_UTF8
)
);

converters.add(converter);
}
}
```

Then define Protocol Buffer messages:

```protobuf
message HelloRequest {
string name = 1;
}

message HelloResponse {
string msg = 1;
}
```

In order to use protobuf messages as entities, we can use gradle plugin `com.google.protobuf` together with [protoc](https://search.maven.org/artifact/com.google.protobuf/protoc) and protoc plugin [protoc-gen-grpc-java](https://search.maven.org/artifact/io.grpc/protoc-gen-grpc-java/).

```java
@RestController
public class APIController {
@RequestMapping(
value = "/hello",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@RequestBody
public HelloResponse hello(@RequestBody HelloRequest req) {
// We can use `HelloResponse` as the return value
return HelloResponse.newBuilder()
.setMsg("Hello " + req.getName())
.build();
}
}
```

```sh
$ curl -X POST -d '{"name": "World"}' http://localhost:8080/hello
{"msg": "Hello World"}
```

## License

MIT