Vous avez raison, le paramètre annoté @RequestBody est censé contenir l'intégralité du corps de la requête et se lier à un objet. Vous devrez donc essentiellement faire appel à vos options.
Si vous tenez absolument à votre approche, il existe cependant une implémentation personnalisée que vous pouvez réaliser :
Disons que c'est votre json :
{
"str1": "test one",
"str2": "two test"
}
et tu veux le lier aux deux paramètres ici :
@RequestMapping(value = "/Test", method = RequestMethod.POST)
public boolean getTest(String str1, String str2)
Définissez d'abord une annotation personnalisée, par exemple @JsonArg
avec le chemin JSON comme chemin d'accès à l'information que vous voulez :
public boolean getTest(@JsonArg("/str1") String str1, @JsonArg("/str2") String str2)
Maintenant, écrivez un Custom HandlerMethodArgumentResolver qui utilise le JsonPath défini ci-dessus pour résoudre l'argument réel :
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import com.jayway.jsonpath.JsonPath;
public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{
private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(JsonArg.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
String body = getRequestBody(webRequest);
String val = JsonPath.read(body, parameter.getMethodAnnotation(JsonArg.class).value());
return val;
}
private String getRequestBody(NativeWebRequest webRequest){
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
String jsonBody = (String) servletRequest.getAttribute(JSONBODYATTRIBUTE);
if (jsonBody==null){
try {
String body = IOUtils.toString(servletRequest.getInputStream());
servletRequest.setAttribute(JSONBODYATTRIBUTE, body);
return body;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return "";
}
}
Maintenant, il suffit de l'enregistrer avec Spring MVC. C'est un peu compliqué, mais cela devrait fonctionner proprement.