/ / Spring MVCでJSONからパラメータを取得する方法は? -json、spring、servlet-3.0

どのように春のmvcでjsonからパラメータを取得するには? - json、spring、servlet-3.0

JSONデータを送信しています:

{
"username":"abc@gmail.com",
"password":"abc"
}

そして、カスタムフィルターでアクセスしたい username そして password

私のフィルターは:

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//code to get parameters from json
}

回答:

回答№1は0

Apache IOユーティリティを使用して、入力ストリームからJSON文字列を取得し、JSON文字列をマップに変換します。

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>

@Override

public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain) throws IOException, ServletException {
try {
String jsonBody = IOUtils.toString(request.getInputStream());
//convert json string to HashMap
//using http://stackoverflow.com/a/22011887/1358551
} catch (Exception e) {
logger.warn("", e);
return new ResponseEntity<String>(e.getMessage(),
HttpStatus.BAD_REQUEST);
}
}

回答№2の場合は0

Google Gsonパーサーの使用をお勧めします

Map<String, String> extractLoginRequest(final ServletRequest request) throws IOException {
final StringBuffer sb = new StringBuffer();
String line = null;
final BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
// as far as I know, gson might not be 100% threadsave
return new Gson().fromJson(sb.toString(), HashMap.class);
}

これで、パラメータにアクセスできます

Map<String, String> loginRequest = extractLoginRequest(request);
loginRequest.get("username")

Mavenを使用している場合、これは使用する可能性のある依存関係です。

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>