嗨,伙计们,我想发一个 JSONArray 使用okhttp。我想这样做:
JSONArray
[ { "name": "john" }, { "food": "burger" } ]
有人能帮我吗?
50few1ms1#
像这样:
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); } } }); }
yeotifhr2#
你可以尝试添加 JSONObject 在数组中,然后将其传递给 JSONArray .像这样:
JSONObject
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);
如果你有更多的项目,那么在循环中运行'js',直到你完成它。
2条答案
按热度按时间50few1ms1#
像这样:
yeotifhr2#
你可以尝试添加
JSONObject
在数组中,然后将其传递给JSONArray
.像这样:
如果你有更多的项目,那么在循环中运行'js',直到你完成它。