JSON在android中合并两个响应

时间:2012-11-13 12:11:10

标签: android json

我正在使用JSON从我的服务器获取响应。 这是代码:

HttpClient httpclient = new DefaultHttpClient();
        HttpClient httpclient2 = new DefaultHttpClient();
        HttpResponse response;
        HttpResponse response2;
        try {
            HttpGet request = new HttpGet(GlobalConfig.getMagazineUrl());
            HttpGet request2 = new HttpGet(GlobalConfig.getMagazinePagesUrl(1));

            request.addHeader("Authorization", "Basic " + Base64.encodeToString(
                                            (GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
            request2.addHeader("Authorization", "Basic " + Base64.encodeToString(
                    (GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
            response = httpclient.execute(request);
            StatusLine statusLine = response.getStatusLine();
            response2 = httpclient2.execute(request2);
            StatusLine statusLine2 = response2.getStatusLine();

            if(statusLine.getStatusCode() == HttpStatus.SC_OK && statusLine2.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ByteArrayOutputStream out2 = new ByteArrayOutputStream();

                response.getEntity().writeTo(out);
                response2.getEntity().writeTo(out2);

                out.close();
                out2.close();
                return parser(out.toString(), out2.toString());

正如您在parser(out.toString(), out2.toString())中看到的,我将两个响应都作为String返回。我想知道如何将这两个JSON响应合并为一个。我不想合并两个字符串,我需要在一个大响应中合并两个JSON响应。这个有可能?如果是,我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

也许这就是你想要的:

...
JSONObject json = new JSONObject();
json.put("response1", new JSONObject(out.toString()));
json.put("response2", new JSONObject(out2.toString()));

现在返回 json.toString()json,具体取决于返回类型。