我想使用Grails-jaxrs plugin实现自定义MessageBodyReaderSupport来从客户端读取UserDto类。
我如何实现UserDtoReader以获取UserDto的实例?
这是我的UserDto类:
public class UserDto {
private String firstName;
private String lastName;
public UserDto() {
firstName = "";
lastName = "";
}
public UserDto(String firstName,
String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
String s = " { User ";
s += "id=" + id + " ";
s += "firstName=" + firstName + " ";
s += "lastName=" + lastName + " ";
s += " User } ";
return s;
}
}
这是我的UserDtoReader类:
@Consumes("application/json")
class UserDtoReader extends MessageBodyReaderSupport<UserDto> {
@Override
public UserDto readFrom(MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException,
WebApplicationException {
// TODO Auto-generated method stub
return null;
}
}
答案 0 :(得分:1)
@Provider
@Consumes(MediaType.APPLICATION_JSON)
public final class UserDtoReader implements MessageBodyReader<UserDto> {
private static final String UTF_8 = "UTF-8";
private Gson gson;
private Gson getGson() {
if (gson == null) {
final GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
}
return gson;
}
public UserDto readFrom(java.lang.Class<UserDto> type,
java.lang.reflect.Type genericType,
java.lang.annotation.Annotation[] annotations, MediaType mediaType,
MultivaluedMap<java.lang.String, java.lang.String> httpHeaders,
java.io.InputStream entityStream) throws IOException {
InputStreamReader streamReader = new InputStreamReader(entityStream,UTF_8);
try {
Type jsonType;
if (type.equals(genericType))
jsonType = type;
else
jsonType = genericType;
UserDto userDto = getGson().fromJson(streamReader, jsonType);
return userDto;
} finally { streamReader.close();}
}
@Override
public boolean isReadable(Class<?> type, Type genericType,
java.lang.annotation.Annotation[] annotations, MediaType mediaType) {
return true;
}
}
您可以从here
下载Google Gson<强>配置强>
JAX-RS资源类和提供程序类的子集(MessageBodyReaders和MessageBodyWriters)。这些类通过javax.ws.rs.core.Application类的扩展在JAX-RS运行时中配置。
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
resources.add(UserDtoReader.class);
return resources;
}
答案 1 :(得分:1)
使用此:
@Consumes("application/json")
class UserDtoReader extends MessageBodyReaderSupport<UserDto> {
@Override
public UserDto readFrom(MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException,
WebApplicationException {
return new JsonSlurper().parse(new InputStreamReader(entityStream))
}
}