Play framework 2.0 -Json處理

 

#JSON請求的處理和服務

 

1.處理Json請求

 

Json請求是使用有效Json數據作爲Http請求的請求體的。它的Content-type頭必須指定爲"text/json"或者"application/json"MIME類型。

默認的,一個動作使用any content 體解析器,你可以把請求(響應)體以Json格式取回來。

 

public static index sayHello() {
	  JsonNode json = request().body().asJson();
	  if(json == null) {
	    return badRequest("Expecting Json data");
	  } else {
	    String name = json.findPath("name").getTextValue();
	    if(name == null) {
	      return badRequest("Missing parameter [name]");
	    } else {
	      return ok("Hello " + name);
	    }
	  }
	}
 

 

 

 

當然了,指定我們自己的BodyParser來讓Play把內容體直接解析爲Json是更好的方式:

@BodyParser.Of(Json.class)
	public static index sayHello() {
	  String name = json.findPath("name").getTextValue();
	  if(name == null) {
	    return badRequest("Missing parameter [name]");
	  } else {
	    return ok("Hello " + name);
	  }
	}
 

注:對於非Json的請求,400 Http響應會被自動返回。

 

你可以在命令行下用curl命令測試:

curl 
	  --header "Content-type: application/json" 
	  --request POST 
	  --data '{"name": "Guillaume"}' 
	  http://localhost:9000/sayHello
 

它返回:

HTTP/1.1 200 OK
	Content-Type: text/plain; charset=utf-8
	Content-Length: 15

	Hello Guillaume
 

 

2.Json響應的服務

 

在以前的例子中我們處理Json請求,但是返回一個"text/plain"的響應。現在我們來發送會一個有效的JsonHttp響應:


@BodyParser.Of(Json.class)
	public static index sayHello() {
	  ObjectNode result = Json.newObject();
	  String name = json.findPath("name").getTextValue();
	  if(name == null) {
	    result.put("status", "KO");
	    result.put("message", "Missing parameter [name]");
	    return badRequest(result);
	  } else {
	    result.put("status", "OK");
	    result.put("message", "Hello " + name);
	    return ok(result);
	  }
	}
 

現在它的響應是:

HTTP/1.1 200 OK
	Content-Type: application/json; charset=utf-8
	Content-Length: 43

	{"status":"OK","message":"Hello Guillaume"}
 

 

發佈了15 篇原創文章 · 獲贊 0 · 訪問量 2699
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章