如何在Android中创建JSONObject?

如何在Android中创建JSONObject?,android,arrays,json,Android,Arrays,Json,我正在使用web服务。我想创建一个JSONObject并通过web服务发送值。怎么做 String redeem = edit_messageredeem.getText().toString(); HttpClient httpclient = new DefaultHttpClient(); String httppostURL = "http:// ...";

我正在使用web服务。我想创建一个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();
                        }
                }
}

如果您想将任何对象转换为JSONOBJET,请下载GSON jar,然后进行如下转换

Gson gson=new Gson();
gson.toJson(Your object that which you want to convert);
我希望这篇文章能对您有所帮助:

创建json对象

JSONObject obj = new JSONObject();
obj.put("key", "your_value");
向json对象添加值

JSONObject obj = new JSONObject();
obj.put("key", "your_value");
请看这个

编辑

这可能对你有帮助

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

这里是我的服务器端代码:

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


在这里,我从数据库中获取值并以字符串形式发送JSON。这对我来说非常有用。只需检查以下内容:

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

List<Your Data Class> data=new ArrayList<Your Data Class>();
并将结果添加到数据中。然后将该数据转换为jsonObject.like

Gson Gson=新Gson; gson.toJsondata


它会像您期望的那样打印:

在向其他人索要代码之前,请先尝试,并确保您阅读了以下内容:您必须在php中使用print\r而不是json\u encode来为您的数据数组进行编码。这里,它说它已被弃用。实际上,我应该创建json数组并通过post发送它。我做了很多尝试,但都没有成功。我不知道为什么他们会像弃用的一样使用。但它仍然有效。只要使用这个。这个肯定对你有帮助:以下是我得到的输出。数组[merchant_id]=>02[merchant_location_id]=>03[user_id]=>04[merchant_kiosk_id]=>04[subscriber_phone]=>999-999-9999,但我希望输出如下:{数据:[[merchant_id]=>02[merchant_location_id]=>03[user_id]=>04[merchant_kiosk_id]=>04[subscriber_phone]=>999-999-9999}您正在获取单个数据。您应该在数组中添加。例如:List data=new ArrayList;并将结果添加到数据中。然后将该数据转换为jsonObject.like gson.toJsondata;以下是我得到的输出。数组[merchant_id]=>02[merchant_location_id]=>03[user_id]=>04[merchant_kiosk_id]=>04[subscriber_phone]=>999-999-9999,但我希望输出如下:{数据:[{[merchant_id]=>02[merchant_location_id]=>03[用户id]=>04[商户信息亭id]=>04[用户电话=>999-999-9999}}如何在数据中添加结果?我犯了一个错误。感谢bdw的帮助。我已经做到了:String[]mStringArray=newstring[data.size];mStringArray=data.toArraymStringArray;forint i=0;i