JSON在Android中合并两个响应 [英] JSON merge two responses in android

查看:362
本文介绍了JSON在Android中合并两个响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using JSON to get response from my server. This is code:

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响应.这个有可能?如果可以,我该怎么做?

As you can see in parser(out.toString(), out2.toString()) I return both responses as String. I would like to know how I can merge this two JSON responses in one. I don't want to merge two strings, I need merge two JSON respons in one big response. This is possible? If yes how I can do that?

推荐答案

也许这就是您想要的:

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

现在根据返回类型返回 json.toString()json.

Now return either json.toString() or json depending on the return type.

这篇关于JSON在Android中合并两个响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆