我遇到了與我的應用程序通信的後端問題。我正在嘗試創建一個JSON請求,將用戶名和密碼值傳遞給服務器。服務器接受這些值並假設返回我映射到用戶對象的用戶。構建JSON請求的問題
現在,服務器已設置好,以便它返回設置爲接收的完全相同的JSON。
我正在使用傑克遜做所有的JSON映射,有沒有辦法改變我傳遞過來匹配下面的JSON的JSON?
這裏是我送
[
{
"name":"username",
"value":"hi"
},
{
"name":"password",
"value":"hi"
}
]
這裏的JSON有什麼JSON是應該看起來像,當它接收到由服務器
{
"password":"hi",
"username":"hi"
}
這裏是我的用戶REST
public static class AuthUser extends
AsyncTask<ArrayList<NameValuePair>, Void, User> {
public interface AuthUserDelegate {
public void getAuthenticatedUser(User user) throws JSONException;
}
AuthUserDelegate delegate;
Context mContext;
public AuthUser(Context context) {
mContext = context;
this.delegate = (AuthUserDelegate) context;
}
@Override
protected User doInBackground(ArrayList<NameValuePair>... params) {
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
User user = null;
String url = ROUTE_USER_AUTH;
HttpPost httppost = new HttpPost(url);
HttpClient httpclient = new DefaultHttpClient();
String UserJSONResponse = null;
try {
String jsonString = mapper.writeValueAsString(params[0]);
StringEntity m_stringEntity = new StringEntity(jsonString);
// UrlEncodedFormEntity m_entity = new UrlEncodedFormEntity(
// params[0]);
httppost.setEntity(m_stringEntity);
httppost.addHeader("Content-type", "application/json");
HttpResponse postResponse = httpclient.execute(httppost);
UserJSONResponse = EntityUtils.toString(postResponse
.getEntity());
user = mapper.readValue(UserJSONResponse, User.class);
Log.e("E AUTH USER", "Status code: "
+ postResponse.getStatusLine().getStatusCode());
Log.e("E AUTH USER", "Auth was sent, Server returned: \n"
+ UserJSONResponse);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
httppost.abort();
Log.e("E IO EXCEPTION", "Error for URL: " + url, e);
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
@Override
protected void onPostExecute(User result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// User user = new User();
// Log.e("AUTH POST USERNAME", result.getUser_name());
try {
delegate.getAuthenticatedUser(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
的主要活動收集信息和執行的AsyncTask
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnSignIn:
username = etUsername.getText().toString().trim();
password = etPassword.getText().toString().trim();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
new UserREST.AuthUser(this).execute(nameValuePairs);
break;
default:
break;
}
}
謝謝。這解決了我的問題。 – 2014-10-28 19:28:08