我大量地將PHP服務器請求轉換爲等效的Java請求。這是一個包含了JSON對象,我需要在Java中複製併發送來自Android設備的代碼:將JSON對象轉換爲JAVA中的等效對象
$(".unableprocess").click(function() {
if (!confirm("Confirm not able to process...!")) {
return false;
} else {
var item_id = $(this).attr('data-id');
var table_id = $(this).attr('table-id');
var data = {
BookOrders: {
item_id: item_id,
table_id: table_id
}
};
$.ajax({
url: //MY URL HERE ,
type: "POST",
data: data,
success: function(evt, responseText) {
location.reload();
}
});
}
});
這裏是試圖執行相同的功能我的Java類。該類擴展了AsyncTask,並且所有的網絡交互都發生在doInBackground()方法中。這裏是我的代碼:
@Override
protected Boolean doInBackground(String... arg0) {
try{
HashMap<String, String> hashMap = new HashMap<String,String>();
JSONObject jsonObject = new JSONObject();
int statusCode;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(tableMateCannotProcessURL);
// JSON object creation begins here:
jsonObject.accumulate("item_id",this.itemId);
jsonObject.accumulate("table_id",this.tableId);
JSONObject jObject = new JSONObject();
jObject.accumulate("BookOrders", jsonObject);
// JSON object ends here
Log.v("ATOMIC BLAST",jObject.toString());
String json = jObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
Integer statusCodeInt = new Integer(statusCode);
Log.v("HTTPResponse",statusCodeInt.toString());
String result= "";
StringBuilder builder = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}
else {
Log.e("==>", "Failed to download file");
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
,我創建看起來像這樣打印出來到控制檯後的JSON對象:
{ 「BookOrders」:{ 「的table_id」: 「1」, 「ITEM_ID」 :「2」}}
將此對象發佈到服務器後,我沒有得到預期的響應。在JAVA中將JSON對象轉換爲等效的JSON對象的正確方法是什麼?任何指導,方向或解決方案將不勝感激。
有你的問題沒有PHP驗證它。它是JavaScript ... – Emmanuel
你可以谷歌它尋找gson例如 – Robert