2017-11-28 4 views
0

私はスプリングブートを使用していますが、jsonobjectタイプのリクエストを使用する場合はrestcontrollerまたはコントローラを作成していますが、タイプを変更すると同じ動作をします。jsonobjectを使用してrestcontrollerを使用したスプリングブート

@Controller 
@RequestMapping("rest/dummy") 

public class CustomerController { 

    @GetMapping("test") 
    public ResponseEntity test(@RequestParam("req") JSONObject inputData) { 
     org.json.JSONObject response = new org.json.JSONObject(); 
     response.put("abc", "123"); 
     return new ResponseEntity(inputData.toString(), HttpStatus.OK); 
    } 

のpom.xml:

<dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-web</artifactId> 
      <version>1.5.8.RELEASE</version> 
</dependency> 
<dependency> 
      <groupId>org.json</groupId> 
      <artifactId>json</artifactId> 
      <version>20171018</version> 
     </dependency> 
     <dependency> 
      <groupId>javax.persistence</groupId> 
      <artifactId>persistence-api</artifactId> 
      <version>1.0.2</version> 
     </dependency> 

私はそれを両方GETとPOSTタイプを使用したくないとも私は、データをその場で変更することができますよう、要求と応答の両方のためにjsonobject使用したいとタイプ。

+0

可能な重複と同じdoesntの仕事を使用して作業ガット(HTTPS:/ /stackoverflow.com/questions/44839753/returning-json-object-as-response-in-spring-boot) – utpal416

答えて

0

それは、Apache-Tomcatの8.0.15、[春ブートにレスポンスとしてJSONオブジェクトを返す]のアパッチ・Tomcatの8.0.49

1

RequestParamでは、URLに追加されたキー値を送信します。 Jsonオブジェクトを送信するには、RequestBodyで送信します。

@RequestBodyを使用し、リクエストの本文部分にJsonを送信します。

+0

私もGET型を使いたいと思っています。この場合、私はURLにpassitする必要があります –

+0

RequestParamは常に文字列になりますが、 Jackson Jsonパーサを使用して、その文字列をメソッドのJsonオブジェクトに変換します。 –

+0

@kapilguptaはあなたのために働いています –

0

パラメータと戻り値として実際のPOJOを使用する方が良い方法です。 Jackson注釈を使用してPOJOを設定します。

とにかく。

@GetMapping("test") 
public ResponseEntity<String> test(@RequestParam("req") JSONObject inputData) { 
    org.json.JSONObject response = new org.json.JSONObject(); 
    response.put("abc", "123"); 
    return ResponseEntity.ok(inputData.toString()); 
} 

は、代わりに

@GetMapping("test") 
public ResponseEntity<SomeOutputDto> test(@RequestParam("req") String inputData) { 

    SomeOutputDto out = new SomeOutputDto(); 
    out.setAbc(123); 
    return ResponseEntity.ok(dto); 
} 

これは、追加のクラスを必要とします:SomeOutputDtoを、その一方で、あなたはあなたのコードをより詳細に制御を持ってこれは動作するはずです。

public class SomeOutputDto { 
    private int abc = 0; 

    public void setAbc(int v) { 
    this.abc = v; 
    } 
    public int getAbc() { return this.abc; } 
} 
+0

試してみましたが、動作しませんでした。また、私は変更を保つことができ、POJO –

関連する問題