您可以将MessageBodyReader与两种用户类型一起使用,一种用于内部 json,另一种用于外部 json
1-创建两种类型而不是扩展字符串(通过委托-使用lombok更容易-):
@RequiredArgsConstructor
public class InternalJSON {
@Delegate
private final String _theJSONStr;
}
@RequiredArgsConstructor
public class ExternalJSON {
@Delegate
private final String _theJSONStr;
}
2- 创建 MessageBodyReader 类型
@Provider
public class MyRequestTypeMapper
implements MessageBodyReader<Object> {
@Override
public boolean isReadable(final Class<?> type,final Type genericType,
final Annotation[] annotations,
final MediaType mediaType) {
// this matches both application/json;internal=true and application/json;internal=false
return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
}
@Override
public Object readFrom(final Class<Object> type,final Type genericType,
final Annotation[] annotations,
final MediaType mediaType,
final MultivaluedMap<String,String> httpHeaders,
final InputStream entityStream) throws IOException,
WebApplicationException {
if (mediaType.getSubType().equals("internal=true") {
// Build an InternalJSON instance parsing entityStream
// ... perhaps using JACKSON or JAXB by hand
} else if (mediaType.getSubType().equals("internal=false") {
// Build an ExternalJSON instance parsing entityStream
// ... perhaps using JACKSON or JAXB by hand
}
}
}
3- 在应用程序中注册您的 MessageBodyReader(这是可选的,因为 jersey 将扫描类路径以查找 @Provider 注释类型
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
...
s.add(MyRequestTypeMapper .class);
return s;
}
4-使用内部和外部json的两种用户类型重新格式化您的休息方法