有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将JSON作为HTTP POST参数发送(Android/Java)

我试图通过HTTP POST参数发送一个JSON对象,其中包含一个JSON数组,其中包含JSON对象

参数的格式(服务器期望的格式)类似于:

{""team"":[
    {""teamid"":""179228"",""position"":1},
    {""teamid"":""218036"",""position"":2},
    {""teamid"":""88109"",""position"":3},
    {""teamid"":""88111"",""position"":4},
    {""teamid"":""165536"",""position"":5},
    {""teamid"":""224645"",""position"":6}
]}

然而,发送的是:

{"team":"[
\"{\\\"position\\\":0,\\\"teamid\\\":\\\"88107\\\"}\",\"{\\\"position\\\":1,\\\"teamid\\\":\\\"88109\\\"}\",\"{\\\"position\\\":2,\\\"teamid\\\":\\\"156714\\\"}\",\"{\\\"position\\\":3,\\\"teamid\\\":\\\"138877\\\"}\",\"{\\\"position\\\":4,\\\"teamid\\\":\\\"168730\\\"}\",\"{\\\"position\\\":5,\\\"teamid\\\":\\\"88110\\\"}\",\"{\\\"position\\\":6,\\\"teamid\\\":\\\"88111\\\"}\",\"{\\\"position\\\":7,\\\"teamid\\\":\\\"134431\\\"}\",\"{\\\"position\\\":8,\\\"teamid\\\":\\\"88112\\\"}\",\"{\\\"position\\\":9,\\\"teamid\\\":\\\"138507\\\"}\",\"{\\\"position\\\":10,\\\"teamid\\\":\\\"138880\\\"}\",\"{\\\"position\\\":11,\\\"teamid\\\":\\\"138881\\\"}\",\"{\\\"position\\\":12,\\\"teamid\\\":\\\"151465\\\"}\",\"{\\\"position\\\":13,\\\"teamid\\\":\\\"151464\\\"}\
"]"}

我构建JSON对象的方式如下:

            JSONArray teamArray = new JSONArray();
            JSONObject jsonRoot = new JSONObject();
            for (int i = 0; i < mTeams.size(); i++) {
                String teamId = null;
                BaseModel data = mTeams.get(i);
                if (data != null && data instanceof TeamModel) {
                    teamId = ((TeamModel) data).getId();
                }
                JSONObject teamObject = new JSONObject();
                try {
                    teamObject.put(
                            getResources().getString(
                                    R.string.sendResortedTeamsPosition), i);
                    teamObject.put(
                            getResources().getString(
                                    R.string.sendResortedTeamsTeamId), teamId);
                    teamArray.put(teamObject);
                } catch (NotFoundException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            try {
                jsonRoot.put("team", teamArray);
                mNameValuePairs.put("teams", jsonRoot);
                    } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

在最后一行(jsonRoot.put("team", teamArray);)中,它的格式与在最后一行中发送的格式相同,但少了一行,因此显然少了一次“解析”

我的HTTP代码的一部分:

String postBody = json.toString();
Log.d("HTTPHelper", "posting JSON: " + postBody);
((HttpPost) httpRequest).setEntity(new StringEntity(postBody));

为什么会这样?是Java吗? 你知道我如何构建正确的JSON吗?或者有什么工作吗

非常感谢


共 (0) 个答案