Domanda

Okay, i worked before with POST but i never had to POST Arrays. (Really)

This is the POST form:

{

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

    },

    {

             "id": 2,
             "level": 4

    }

    ]

}

So i have to send a JSONObject with an "about" key and value, and a "sports" JSONArray, that could be null too.

I tried the followings:

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

So my question is how to achive this POST form?

My posting:

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);
È stato utile?

Soluzione

Here I have built up the JSONObject manually for you:

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){
}

As you can see, I have built some parts of the json from string, but you can create also an empty object and fill it with data ( as I did in the case of the jsonarray )

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top