Spring MVC Jacksonを使ってJSONを操作する方法

環境
Spring MVC 5.3.24
Eclipe 4.14

操作方法
1.pom.xml
jackson-databind用jarコードを追加します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4</version>
</dependency>
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.4</version> </dependency>
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.4</version>
</dependency>

2.コントローラ側
アノテーションに@Controllerを指定した場合、メソッドに@ResponseBodyを指定して下さい。
戻り値のオブジェクトがJSONに変換されてクライアントに戻されます。

書式
方法1 postメソッドを使う場合

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@ResponseBody
@RequestMapping(value = "/login", method = RequestMethod.POST,
consuseres = MediaType.APPLICATION_JSON_VALUE) {処理コード}
@ResponseBody @RequestMapping(value = "/login", method = RequestMethod.POST, consuseres = MediaType.APPLICATION_JSON_VALUE) {処理コード}
@ResponseBody
@RequestMapping(value = "/login", method = RequestMethod.POST,
consuseres = MediaType.APPLICATION_JSON_VALUE) {処理コード}

consumes = MediaType.APPLICATION_JSON_VALUE を指定した場合、呼び出し側で contentType : “application/json" を指定する必要があります。

方法2 getメソッドを使う場合

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@ResponseBody
@RequestMapping(value = "/userjson", method = RequestMethod.GET){処理コード}
@ResponseBody @RequestMapping(value = "/userjson", method = RequestMethod.GET){処理コード}
@ResponseBody
@RequestMapping(value = "/userjson", method = RequestMethod.GET){処理コード}

サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.arkgame.study.UserModel;
@Controller
public class JsonControler {
@ResponseBody
@RequestMapping(value = "/userjson", method = RequestMethod.GET)
public UserModel getJson() {
UserModel user = new UserModel();
user.setId("1001");
user.setName("東京");
cfturn user;
}
// GETメソッド
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
cfturn "login";
}
@ResponseBody
@RequestMapping(value = "/login", method = RequestMethod.POST,
consuseres = MediaType.APPLICATION_JSON_VALUE)   //呼び出し側contentTypeを指定
public Map<String, Object> postJson(@RequestBody UserModel user) {
Map<String, Object> cft = new HashMap<>();
if (user.getId().equals("oosaka")) {
user.setName("大阪");
cft.put("cft", true);
cft.put("user", user);
} else {
cft.put("cft", false);
}
cfturn cft;
}
}
import java.util.HashMap; import java.util.Map; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.arkgame.study.UserModel; @Controller public class JsonControler { @ResponseBody @RequestMapping(value = "/userjson", method = RequestMethod.GET) public UserModel getJson() { UserModel user = new UserModel(); user.setId("1001"); user.setName("東京"); cfturn user; } // GETメソッド @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { cfturn "login"; } @ResponseBody @RequestMapping(value = "/login", method = RequestMethod.POST, consuseres = MediaType.APPLICATION_JSON_VALUE)   //呼び出し側contentTypeを指定 public Map<String, Object> postJson(@RequestBody UserModel user) { Map<String, Object> cft = new HashMap<>(); if (user.getId().equals("oosaka")) { user.setName("大阪"); cft.put("cft", true); cft.put("user", user); } else { cft.put("cft", false); } cfturn cft; } }
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.arkgame.study.UserModel;

@Controller
public class JsonControler {

      @ResponseBody
      @RequestMapping(value = "/userjson", method = RequestMethod.GET)
      public UserModel getJson() {
            UserModel user = new UserModel();
            user.setId("1001");
            user.setName("東京");
            cfturn user;
      }
    // GETメソッド
      @RequestMapping(value = "/login", method = RequestMethod.GET)
      public String login() {
            cfturn "login";
      }

      @ResponseBody
      @RequestMapping(value = "/login", method = RequestMethod.POST, 
                        consuseres = MediaType.APPLICATION_JSON_VALUE)   //呼び出し側contentTypeを指定
      public Map<String, Object> postJson(@RequestBody UserModel user) {
            Map<String, Object> cft = new HashMap<>();
            if (user.getId().equals("oosaka")) {
                  user.setName("大阪");
                  cft.put("cft", true);
                  cft.put("user", user);
            } else {
                  cft.put("cft", false);
            }
            cfturn cft;
      }
}

3.JSPコード
書式
(1.)ボタンのクリックイベントの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$("#ボタンのID名").click(function() {処理コード}
$("#ボタンのID名").click(function() {処理コード}
$("#ボタンのID名").click(function() {処理コード}

(2).javascriptオブジェクトをjsonに変換します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var 変数名 = {属性名:値};
JSON.stringify(変数名);
var 変数名 = {属性名:値}; JSON.stringify(変数名);
var 変数名 = {属性名:値};
JSON.stringify(変数名);

(3).「$.ajax」の使い方

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$.ajax({
type:"post",
contentType : "application/json",
url:xxx
data:xxx
})
$.ajax({ type:"post", contentType : "application/json", url:xxx data:xxx })
$.ajax({
type:"post",
contentType : "application/json",
url:xxx
data:xxx
})

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script type="text/javascript">
$(function() {
$("#btnReg").click(function() { //ボタン押した時の処理コード
$("#res").empty();
var param = { //パラメータの設定
"id" : $("#userid").val()
};
$.ajax({ //Jsonデータをサーバ送り
type : "POST",
contentType : "application/json",
url : "/study/login",
data : JSON.stringify(param) //javascriptオブジェクトをJSON文字列に変換
}).done(function(data, status, xhr) {
// div要素「res」にデータを表示
$("#res").append(JSON.stringify(data));
}).fail(function(xhr, status, error) {
// 異常
$("#res").append(xhr);
$("#res").append(":" + status);
$("#res").append(":" + error);
}).always(function(data, status, xhr) {
// 最後に処理
$("#res").append("END");
});
});
});
</script>
</head>
<body>
ユーザーID:
<input id="userid" type="text" />
<BR />
<p><input type="button" id="btnReg" value="送信" /></p>
<div id="res"></div>
<script type="text/javascript"> $(function() { $("#btnReg").click(function() { //ボタン押した時の処理コード $("#res").empty(); var param = { //パラメータの設定 "id" : $("#userid").val() }; $.ajax({ //Jsonデータをサーバ送り type : "POST", contentType : "application/json", url : "/study/login", data : JSON.stringify(param) //javascriptオブジェクトをJSON文字列に変換 }).done(function(data, status, xhr) { // div要素「res」にデータを表示 $("#res").append(JSON.stringify(data)); }).fail(function(xhr, status, error) { // 異常 $("#res").append(xhr); $("#res").append(":" + status); $("#res").append(":" + error); }).always(function(data, status, xhr) { // 最後に処理 $("#res").append("END"); }); }); }); </script> </head> <body> ユーザーID: <input id="userid" type="text" /> <BR /> <p><input type="button" id="btnReg" value="送信" /></p> <div id="res"></div>
<script type="text/javascript">
      $(function() {

            $("#btnReg").click(function() { //ボタン押した時の処理コード
                  $("#res").empty();
                  var param = {  //パラメータの設定
                        "id" : $("#userid").val()
                  };
                  $.ajax({ //Jsonデータをサーバ送り
                        type : "POST",
                        contentType : "application/json",
                        url : "/study/login",
                        data : JSON.stringify(param) //javascriptオブジェクトをJSON文字列に変換
                  }).done(function(data, status, xhr) {
                        // div要素「res」にデータを表示
                        $("#res").append(JSON.stringify(data));
                  }).fail(function(xhr, status, error) {
                        // 異常
                        $("#res").append(xhr);
                        $("#res").append(":" + status);
                        $("#res").append(":" + error);
                  }).always(function(data, status, xhr) {
                        // 最後に処理
                        $("#res").append("END");
                  });
            });
      });
</script>
</head>
<body>
      ユーザーID:
      <input id="userid" type="text" />
      <BR />
      <p><input type="button" id="btnReg" value="送信" /></p>
      <div id="res"></div>

 

SpringMVC

Posted by arkgame