内部json用と外部json用の2つのユーザータイプとともにMessageBodyReaderを使用できます
1- String を拡張するよりも 2 つの型を作成します (委譲を介して -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- Application で MessageBodyReader を登録します (jersey は @Provider 注釈付きの型のクラスパスをスキャンするため、これはオプションです
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
...
s.add(MyRequestTypeMapper .class);
return s;
}
4-内部および外部jsonの2つのユーザータイプを使用して、残りのメソッドを再フォーマットします