Reputation: 43
Hi guys I was trying to post a JSONArray
using OkHttp. I want to do like this:
[
{
"name": "john"
},
{
"food": "burger"
}
]
Can anyone help me out?
Upvotes: 1
Views: 695
Reputation: 492
Something like this:
public void sendRequest(String route) {
OkHttpClient client = new OkHttpClient();
String url = baseUrl + route;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", String.valueOf(username.getText()))
.addFormDataPart("password", String.valueOf(password.getText()))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("Error", "Something Went Wrong");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String myresponse = response.body().string();
try {
JSONArray all = new JSONArray(myresponse);
// Do whatever
} catch (JSONException e) {
e.printStackTrace();
}
} else {
String errorBodyString = response.body().string();
Log.d("Error", errorBodyString);
}
}
});
}
Upvotes: -1
Reputation: 373
You can try adding a JSONObject
in an array and then pass it to your JSONArray
.
Something like this:
JSONArray list = new JSONArray();
JSONObject js = new JSONObject();
try {
js.put("name", "john");
} catch (JSONException e) {
e.printStackTrace();
}
list.put(js);
js = new JSONObject();
try {
js.put("food", "burger");
} catch (JSONException e) {
e.printStackTrace();
}
list.put(js);
Log.e(TAG, "found json array " + list);
and if you have more items, then run the `js' in a loop until you are done with it.
Upvotes: 2