如何在Android中创建JSONObject?

时间:2015-01-30 11:18:57

标签: android arrays json

我正在使用网络服务。我想创建一个JSONObject并通过Web服务发送值。怎么做?

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

4 个答案:

答案 0 :(得分:1)

创建json对象

JSONObject obj = new JSONObject();

将值添加到json对象

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

请参阅此answer

<强> EDITED

这可能对您有所帮助

JSONArray array = new JSONArray();
array.put(obj);
JSONObject par_obj= new JSONObject();
par_obj.put("data",array); 

答案 1 :(得分:0)

如果要将对象转换为JSONObject,请下载GSON jar,然后转换为

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

我希望这个会对你有所帮助:)。

答案 2 :(得分:0)

这是我的服务器端代码:

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

}

这里我从dataBase获取值并将JSON发送为String.It对我来说很棒。只需检查一下:)

答案 3 :(得分:0)

您正在获取单个数据。您应该在数组中添加。例如:

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

并在数据中添加结果。然后将该数据转换为jsonObject.like

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

它会打印出你的期望:)