2014-06-09 3 views
-3

나는 PHP 서버 요청을 동등한 Java 요청으로 변환하는 데 막대한 노력을 기울이고있다. 여기자바에서 JSON 객체를 동등한 것으로 변환

$(".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(); 

        } 
       }); 
      } 
}); 

와 동일한 기능을 수행하려고 내 자바 클래스가 : 이것은 내가 안드로이드 기기에서 자바의 복제 및 전송에 필요한 JSON 개체를 포함하는 코드입니다. 이 클래스는 AsyncTask를 확장하고 모든 네트워크 상호 작용은 doInBackground() 메소드에서 발생합니다. "1", "ITEM_ID"

@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"여기 내 코드입니다 : "2"}}

이 개체를 서버에 게시 한 후 예상되는 응답을 얻지 못했습니다. JSON 객체를 JAVA의 동등한 JSON 객체로 변환하는 적절한 방법은 무엇입니까? 모든 지침, 방향 또는 해결책은 가장 높이 평가 될 것입니다.

+1

사용하여 유효성을 검사 할 수 있습니다 경우 당신이 확실하지 않은 경우. 그것은 자바 스크립트입니다 ... – Emmanuel

+0

당신은 예를 들어 gson 찾아 – Robert

답변

0

php를 버전 5.4로 업데이트하는 데 도움이되었습니다. 이 버전에서 json_encode($x, JSON_PRETTY_PRINT)은 필요에 따라 작동합니다.

+1

구글 수 있습니다 그것은 불가능하다고 생각하지만,이 대답은 질문보다 더 – Emmanuel

0

JSON은 정확하지만 Object의 Object입니다.

JSONObject json = new JSONObject(yourdata); 
JSONObject jsonTable = new JSONObject(json.getString("BookOrders")); 

Log.d("JsonDebug", "json:" + jsonTable.toString()); 

당신이 된 JSONObject이 있거나 배열은 당신이 당신의 질문에 아무런 PHP가 없습니다

String data = "{ ... }"; 
Object json = new JSONTokener(data).nextValue(); 
if (json instanceof JSONObject) 
//you have an object 
else if (json instanceof JSONArray) 
//you have an array 
+0

당신은 질문에, 오른쪽에 PHP가 없다는 걸 알지? – Emmanuel

+0

미안합니다. PHP 파일을 아약스로 생각하고 JSON으로 변환했습니다. 그렇지 않다면, 미안 해요. 어쨌든. 필자는 내 대답을 업데이트했습니다. 고맙습니다 –

관련 문제