Coova
Coova

Reputation: 1858

Issue structuring JSON request

I am running into an issue communicating with a back-end with my app. I am trying to create a JSON request that passes a username and a password value to the server. The server than takes these values and is suppose to return the User which I map to a User Object.

Right now the server is set up so that it returns the exact same JSON that is is set up to receive.

I am using Jackson to do all the JSON mapping, is there a way to change the JSON I am passing over to match the JSON below?

HERE IS THE JSON I AM SENDING

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

HERE IS WHAT THE JSON IS SUPPOSED TO LOOK LIKE WHEN IT IS RECEIVED BY SERVER

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

HERE IS MY USER 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();
            }

        }
    }

THE MAIN ACTIVITY TO GATHER INFORMATION AND EXECUTE 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;
    }

}

Upvotes: 0

Views: 42

Answers (2)

MrPancake
MrPancake

Reputation: 84

Instead of using NameValuePair use JSONObject.

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

this returns what you're looking for.

Upvotes: 0

ToYonos
ToYonos

Reputation: 16833

Define your own JSONObject :

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

And execute your task like this :

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

The task should look like this :

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());
            // [...]

Upvotes: 2

Related Questions