🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Jersey + Google Gson 示例 > 原文: [https://howtodoinjava.com/jersey/jax-rs-gson-example/](https://howtodoinjava.com/jersey/jax-rs-gson-example/) 本教程说明如何将 [**google Gson**](//howtodoinjava.com/best-practices/google-gson-tutorial-convert-java-object-to-from-json/) 与 Jersey2.x 结合使用。 还有其他一些 Java 库也可以执行此转换,例如 [MOXy](//howtodoinjava.com/jersey/jax-rs-jersey-moxy-json-example/) ,Jackson 或 [JSONP](//howtodoinjava.com/jersey/jax-rs-jersey-jsonp-example/) ; 但是 Gson 很少需要任何预先注解的 Java 类或 Java 类源代码。 ```java Table of Contents Maven dependencies/changes Create Gson Provider Register Gson Provider Extending Gson Functionality Demo ``` Jersey(Jersey)不提供对 Gson 的任何内置支持,因为它提供了 MOXy 和 JSONP 等。但是,Jersey(Jersey)提供了发现机制,可通过实现一些接口并将实现注册到应用配置中来扫描应用的各种可配置组件。 通过实现接口`javax.ws.rs.ext.MessageBodyWriter`和`javax.ws.rs.ext.MessageBodyReader`,可以将 Gson 与 Jersey 一起用作 JSON 序列化器/反序列化器,并可以使用`@Provider`注解或`ResourceConfig.register()`方法注册配置。 让我们一步一步地查看所有步骤。 ## Maven 依赖 首先包括 Gson 依赖项。 ```java <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency> ``` ## 创建 Gson 供应器 现在,创建一个实现接口`javax.ws.rs.ext.MessageBodyWriter`和`javax.ws.rs.ext.MessageBodyReader`的类,并覆盖其方法。 ```java package com.howtodoinjava.jersey.provider; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonMessageBodyHandler implements MessageBodyWriter<Object>, MessageBodyReader<Object> { private static final String UTF_8 = "UTF-8"; private Gson gson; //Customize the gson behavior here private Gson getGson() { if (gson == null) { final GsonBuilder gsonBuilder = new GsonBuilder(); gson = gsonBuilder.disableHtmlEscaping() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .setPrettyPrinting() .serializeNulls() .create(); } return gson; } @Override public boolean isReadable(Class<?> type, Type genericType, java.lang.annotation.Annotation[] annotations, MediaType mediaType) { return true; } @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) { InputStreamReader streamReader = null; try { streamReader = new InputStreamReader(entityStream, UTF_8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { Type jsonType; if (type.equals(genericType)) { jsonType = type; } else { jsonType = genericType; } return getGson().fromJson(streamReader, jsonType); } finally { try { streamReader.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } @Override public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8); try { Type jsonType; if (type.equals(genericType)) { jsonType = type; } else { jsonType = genericType; } getGson().toJson(object, jsonType, writer); } finally { writer.close(); } } } ``` ## 注册 Gson 供应器 现在使用应用资源配置在上述类中注册。 ```java package com.howtodoinjava.jersey; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.server.ResourceConfig; import com.howtodoinjava.jersey.provider.GsonMessageBodyHandler; public class CustomApplication extends ResourceConfig { public CustomApplication() { packages("com.howtodoinjava.jersey"); register(LoggingFilter.class); register(GsonMessageBodyHandler.class); } } ``` ## 扩展 Gson 功能 您可以随时在`GsonMessageBodyHandler.getGson()`方法中扩展/自定义 Gson 行为。 ```java private Gson getGson() { if (gson == null) { final GsonBuilder gsonBuilder = new GsonBuilder(); gson = gsonBuilder.disableHtmlEscaping() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .setPrettyPrinting() .serializeNulls() .create(); } return gson; } ``` ## 演示 现在,如果您通过任何 REST 客户端访问任何 REST 资源,您将获得所需的 JSON 输出。 #### 点击 URL:`http://localhost:8080/JerseyDemos/rest/employees` 现在的输出将是: ```java { "EmployeeList": [ { "Id": 1, "Name": "Lokesh Gupta" }, { "Id": 2, "Name": "Alex Kolenchiskey" }, { "Id": 3, "Name": "David Kameron" } ] } ``` **祝您学习愉快!**