0

さて、以前は POST を使用していましたが、配列を POST する必要はありませんでした。(本当)

これは POST フォームです。

{

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

    },

    {

             "id": 2,
             "level": 4

    }

    ]

}

したがって、「about」キーと値を含む JSONObject と、null の可能性がある「sports」JSONArray を送信する必要があります。

私は以下を試しました:

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 フォームを達成する方法ですか?

私の投稿:

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);
4

1 に答える 1

1

ここでは、JSONObject を手動で作成しました。

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 の場合と同様)。

于 2014-06-24T22:27:43.703 に答える