发布结构化JSON请求

时间:2014-10-28 17:22:33

标签: java android json

我遇到了与我的应用后端通信的问题。我正在尝试创建一个JSON请求,将用户名和密码值传递给服务器。服务器取这些值并假设返回我映射到用户对象的用户。

现在服务器已设置好,以便返回设置为接收的完全相同的JSON。

我正在使用Jackson进行所有JSON映射,有没有办法更改我传递的JSON以匹配下面的JSON?

这是我发送的JSON

[  
   {  
      "name":"username",
      "value":"hi"
   },
   {  
      "name":"password",
      "value":"hi"
   }
]

这里是服务员收到JSON所支持的东西

{  
   "password":"hi",
   "username":"hi"
}

这是我的用户休息

    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;
    }

}

2 个答案:

答案 0 :(得分:2)

定义您自己的JSONObject:

JSONObject input = new JSONObject();
input.put("username", "hi");
input.put("password", "hi");

执行你的任务:

new UserREST.AuthUser(this).execute(input);

任务应如下所示:

public static class AuthUser extends AsyncTask<JSONObject, Void, User>
{
    // [...]

    @Override
    protected User doInBackground(JSONObject... params)
    {
        User user = null;
        String url = ROUTE_USER_AUTH;
        HttpPost httppost = new HttpPost(url);
        HttpClient httpclient = new DefaultHttpClient();
        String UserJSONResponse = null;

        try
        {
            StringEntity m_stringEntity = new StringEntity(params[0].toString());
            // [...]

答案 1 :(得分:0)

而不是使用NameValuePair使用JSONObject。

public String getJSONAuth(String user, String pass) {
    JSONObject jo = new JSONObject();
    jo.putString("username", user);
    jo.putString("password", pass);
    return jo.toString();
}

这将返回您要查找的内容。