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.
- Host: GitHub
- URL: https://github.com/kaelzhang/java-fastjson-protobuf
- Owner: kaelzhang
- License: other
- Created: 2018-08-23T12:37:37.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-04-12T11:00:32.000Z (almost 7 years ago)
- Last Synced: 2025-03-25T13:16:16.847Z (about 1 year ago)
- Topics: fastjson, fastjson-android, grpc, java, protobuf
- Language: Java
- Homepage:
- Size: 95.7 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: HISTORY.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://travis-ci.org/kaelzhang/java-fastjson-protobuf)
[](https://codecov.io/gh/kaelzhang/java-fastjson-protobuf)
[](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