簡體   English   中英

Spring mvc中的JSON數據綁定

[英]JSON data binding in spring mvc

我使用以下代碼從我的Spring MVC控制器中的android應用程序接收了json數據。

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestHeader;

@RequestMapping(method = RequestMethod.POST, produces = "application/json")
public @ResponseBody String getMethod(@RequestHeader(value="json") String    
headerStr) {
System.out.println("POST");
System.out.println(headerStr);
return "hello";
}

System.out.println(headerStr)的輸出為

{"action":"check_login","password":"test","username":"test"}

但我想將這個json數據綁定到下面的類。

public class LoginRequest {
private String action;
private String username;
private String password;

public String getAction() {
return action;
}

public void setAction(String action) {
this.action = action;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

在我的POM.xml中

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>

以下是我的Android代碼

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    HttpClient httpclient = new DefaultHttpClient(httpParams);
    HttpPost httppost = new HttpPost( "http://localhost:8080/datarequest");
    JSONObject json = new JSONObject();


        json.put("action", "check_login");
        json.put("username","name");
        json.put("password", "password");


    JSONArray postjson = new JSONArray();
    postjson.put(json);

    httppost.setHeader("json", json.toString());
    httppost.getParams().setParameter("jsonpost", postjson);

    System.out.println(postjson);
    HttpResponse response = httpclient.execute(httppost);

如何解決這個問題呢?

您應該將方法中的參數更改為

public @ResponseBody String getMethod(@RequestBody LoginRequest loginRequest) 

這樣, LoginRequest類將被實例化並綁定到json值,其中鍵與屬性匹配

此外,請確保將json作為正文的一部分發送,添加以下內容

StringEntity se = new StringEntity(json.toString(), "UTF8");  
se.setHeader("Content-type", "application/json");
post.setEntity(se);

HttpResponse response = httpclient.execute(httppost);之前HttpResponse response = httpclient.execute(httppost);

使用Jackson ObjectMapper

ObjectMapper mapper = new ObjectMapper();
LoginRequest login = mapper.readValue(headerStr, LoginRequest.class);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM