-6

I am working with web services. I want to create a JSONObject and send the values through web service. How to do it?

 String redeem = edit_messageredeem.getText().toString();
                     HttpClient httpclient = new DefaultHttpClient();
                     String httppostURL = "http:// ...";
                        HttpPost httppost = new HttpPost(httppostURL);
                        Log.v(TAG, "postURL: " + httppost);   

                               List<NameValuePair> data2 = new ArrayList<NameValuePair>(5);
                               data2.add(new BasicNameValuePair("merchant_id", "02"));
                               data2.add(new BasicNameValuePair("merchant_location_id", "03"));
                               data2.add(new BasicNameValuePair("user_id", "04"));
                               data2.add(new BasicNameValuePair("merchant_kiosk_id", "04"));
                               data2.add(new BasicNameValuePair("coupon_code", redeem));
                               httppost.setHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded;charset=UTF-8");
                               httppost.setEntity(new UrlEncodedFormEntity(data2 , "UTF-8"));               
                    //         httppost.setEntity(new UrlEncodedFormEntity(data));
                    //         httpclient.execute(httppost);                 
                               HttpResponse response = httpclient.execute(httppost);
                               HttpEntity resEntity = response.getEntity();  
                               if (resEntity != null) {                               
                                   String responseStr = EntityUtils.toString(resEntity).trim();
                                   Log.v(TAG, "Response: " +  responseStr);
                                   Log.i("TAG",""+response.getStatusLine().getStatusCode());
                                   Toast.makeText(RedeemActivity.this,  responseStr, Toast.LENGTH_LONG).show(); 
                                   // you can add an if statement here and do other actions based on the response
                               }               
                               edit_messageredeem.setText(""); //reset the message text field
                         //      Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
                               Toast.makeText(RedeemActivity.this, "Data: " +data2,Toast.LENGTH_LONG).show();

                        } catch (ClientProtocolException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Throwable t) {
                            Toast.makeText(RedeemActivity.this, "Request failed: " + t.toString(),
                                    Toast.LENGTH_LONG).show();
                        }
                }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Priyasha
  • 3
  • 4

4 Answers4

1

Creating json object

JSONObject obj = new JSONObject();

adding values into json object

obj.put("key", "your_value");

please see this answer

EDITED

This may be help you

JSONArray array = new JSONArray();
array.put(obj);
JSONObject par_obj= new JSONObject();
par_obj.put("data",array); 
Community
  • 1
  • 1
uday
  • 1,348
  • 12
  • 27
  • The following is what I am getting as output. Array ( [merchant_id] => 02 [merchant_location_id] => 03 [user_id] => 04 [merchant_kiosk_id] => 04 [subscriber_phone] => 999-999-9999 ) But instead of this I want the output as follows: { "data": [ { [merchant_id] => 02 [merchant_location_id] => 03 [user_id] => 04 [merchant_kiosk_id] => 04 [subscriber_phone] => 999-999-9999 } ] } – Priyasha Jan 30 '15 at 13:49
0

If you want to convet any object to JSONObcjet Download GSON jar then convert like

Gson gson=new Gson();
gson.toJson(Your object that which you want to convert);

I hope this one will help to you :)

user3515851
  • 469
  • 1
  • 4
  • 14
  • https://code.google.com/p/google-gson/downloads/detail?name=google-gson-2.2.4-release.zip& here it says it is deprecated. Actually I am supposed to create json array and send it through post. I tried a lot but couldn't make it work. – Priyasha Jan 30 '15 at 12:07
  • I don't know why they are puting like deprecated.but It's still working.just use this.surely this one help to you :) – user3515851 Jan 30 '15 at 12:13
  • The following is what I am getting as output. Array ( [merchant_id] => 02 [merchant_location_id] => 03 [user_id] => 04 [merchant_kiosk_id] => 04 [subscriber_phone] => 999-999-9999 ) But instead of this I want the output as follows: { "data": [ { [merchant_id] => 02 [merchant_location_id] => 03 [user_id] => 04 [merchant_kiosk_id] => 04 [subscriber_phone] => 999-999-9999 } ] } – Priyasha Jan 30 '15 at 13:50
  • you are getting single data.you should add within array.For ex: `List data=new ArrayList(); ` and add your result within data. then convert that data as jsonObject.like `gson.toJson(data);` – user3515851 Jan 31 '15 at 06:54
0

Here my server side code:

@Path("chat")
public class Chat {

Statement statement;
Gson gson=new Gson();



@Path("/getPrevious")
@GET
public String getPreviousChat(@QueryParam("senderId")String senderId,
                @QueryParam("receiverId")String receiverId){

    ChatDataList list=new ChatDataList();
    ArrayList<ChatData> datas=new ArrayList<ChatData>();

    try {
        statement=DBConn.getConnection();
        ResultSet rs=statement.executeQuery("select * from chat where sender_id="+senderId
                +" AND receiver_id="+receiverId+" ORDER BY id DESC limit 50");
        while (rs.next()) {
            ChatData data=new ChatData();
            data.setSenderId(rs.getInt("sender_id"));
            data.setReceiverId(rs.getInt("receiver_id"));
            data.setMsg(rs.getString("msg"));
            datas.add(data);
        }
        list.setChatList(datas);

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return gson.toJson(list);
}

}

Here I getting value from dataBase and send JSON as String.It working awesome to me.Just check this :)

user3515851
  • 469
  • 1
  • 4
  • 14
0

you are getting single data.you should add within array.For ex:

List<Your Data Class> data=new ArrayList<Your Data Class>();

and add your result within data. then convert that data as jsonObject.like

Gson gson=new Gson(); gson.toJson(data);

It will print like your expectation :)

user3515851
  • 469
  • 1
  • 4
  • 14
  • how to add result within data? I am getting error. Thanks bdw for your help. – Priyasha Feb 02 '15 at 13:17
  • I have done this: String[] mStringArray = new String[data.size()]; mStringArray = data.toArray(mStringArray); for(int i = 0; i < mStringArray.length ; i++){ Log.d("string is",(mStringArray[i]));} – Priyasha Feb 02 '15 at 13:50
  • you have to use pojo class within list.just search how to use POJO class :) – user3515851 Feb 03 '15 at 06:10
  • Thanks a ton. It worked! :) I did: List nvps = new ArrayList (); nvps.add(new BasicNameValuePair("data", data1.toString())); httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); – Priyasha Feb 03 '15 at 09:12