2014-02-10 1 views
0

그래, POST를 사용하기 전에 작업했지만 POST Array를 사용할 필요가 없었습니다. (정말)POST를 JSONArray와 함께 사용하는 방법

이것은 POST 양식입니다 :

{ 

    "about": "about me", 
    "sports": [ 
    { 
      "id": 1, 
      "level": 3 

    }, 

    { 

      "id": 2, 
      "level": 4 

    } 

    ] 

} 

그래서 내가 키와 값, 그리고 "스포츠"JSONArray "에 대해"그건 너무 null이 될 수 있습니다으로 된 JSONObject를 보낼 수 있습니다.

1.

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); 
    nameValuePair.add(new BasicNameValuePair("about", "Lorem ipsum about me")); 
    nameValuePair.add(new BasicNameValuePair("sports", "[]")); 

2.

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); 
     nameValuePair.add(new BasicNameValuePair("about", "Lorem ipsum about me")); 
     nameValuePair.add(new BasicNameValuePair("sports", new ArrayList<NameValuePair>())); 
                ///Of course its silly it doesnt work at all 

그래서 내 질문이 POST 양식을 실현하려 방법은 다음과 같습니다

나는 다음과 시도?

내 게시물 : 당신을 위해 수동으로 된 JSONObject를 구축했다

다음
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
httppost.addHeader("Content-Type", "application/json"); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
HttpResponse httpResponse = httpclient.execute(httppost); 
+0

UrlEncodedFormEntity는 JSON이 아닙니다. StringEntity 및 JSONObject.toString()을 사용하십시오. – njzk2

답변

1

:

try{ 
    JSONObject attr1 = new JSONObject("{\"id\": 1, \"level\":3 }"); 
    JSONArray sports = new JSONArray(); 
    sports.put(attr1); 
    //sports.put(attr2); and so on 
    JSONObject yourObject = new JSONObject("{\"about\": \"About me\"}"); 
    yourObject.put("sports", sports); 

    String url = yourObject.toString(); 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(url); 
    HttpResponse httpResponse = httpclient.execute(httppost); 

}catch(Exception e){ 
} 

당신이 볼 수 있듯이, 나는 문자열에서 JSON의 일부를 구축하지만, 빈 개체를 만들어 데이터로 채울 수 있습니다 (jsonarray의 경우처럼)

관련 문제