Java 从HttpResponse获取json

Java 从HttpResponse获取json,java,android,json,Java,Android,Json,看起来很有意思。只有一个小问题:字符串用括号括起来[]。我应该手动删除它们吗?它们是由php:sjson\u encode()生成的。如果我从web服务返回json字符串,我通常希望将其返回到json对象,如下所示: String json = EntityUtils.toString(response.getEntity()); 使用这个类,您可以从服务器或资产文件夹获取JSON数据。它可以很容易地更改为只有一个或另一个。如果您需要适配器,请使用该适配器 @覆盖 已创建ActivitySta

看起来很有意思。只有一个小问题:字符串用括号括起来
[]
。我应该手动删除它们吗?它们是由php:s
json\u encode()

生成的。如果我从web服务返回json字符串,我通常希望将其返回到json对象,如下所示:

String json = EntityUtils.toString(response.getEntity());

使用这个类,您可以从服务器或资产文件夹获取JSON数据。它可以很容易地更改为只有一个或另一个。如果您需要适配器,请使用该适配器

@覆盖
已创建ActivityState上的公共无效(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
Bundle getArgs=this.getArguments();
String URI=getArgs.getString(KEY_URI);//或者您可以硬编码,或者以任何方式获取字符串。
新建GetJSONTask().execute(URI);
}
类GetJSONTask扩展了AsyncTask{
受保护的字符串doInBackground(字符串…arg0){
字符串uri=arg0[0];
InputStream=null;
如果(uri.contains(“http”)==true){//从URL获取JSON
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(uri);
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
BufferedReader rd=新的BufferedReader(新的InputStreamReader(即“UTF-8”));
而((line=rd.readLine())!=null){
json+=行;
}
rd.close();
返回json;
}捕获(例外e){
e、 printStackTrace();
返回null;
}
}else{//从资产获取JSON
Writer-Writer=新的StringWriter();
char[]buffer=新字符[1024];
试一试{
InputStream jsonFile=getActivity().getAssets().open(uri);
Reader Reader=新的BufferedReader(新的InputStreamReader(jsonFile,“UTF-8”);
int n;
while((n=读卡器读取(缓冲区))!=-1){
writer.write(缓冲区,0,n);
}
jsonFile.close();
}捕获(IOE异常){
e、 printStackTrace();
}
json=writer.toString();
//返回JSON字符串
返回json;
}
}
@凌驾
受保护的void onPostExecute(字符串结果){
试一试{
显示数据(结果);
}捕获(JSONException e){
e、 printStackTrace();
Toast.makeText(getActivity(),“出错了”,Toast.LENGTH_SHORT.show();
}
}
}
私有void showData(字符串json)抛出JSONException{
JSONObject o=新的JSONObject(json);
JSONArray数据=o.getJSONArray(“结果”);
}
}

问题出在我的php文件中。从json编码的对象中删除容器数组使我的java代码正常工作。

我认为您遇到的问题与我刚才遇到的问题类似。如果您运行:

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Bundle getArgs = this.getArguments();
        String URI = getArgs.getString(KEY_URI);//OR YOU CAN HARD CODE THIS OR GET THE STRING ANYWAY YOU LIKE.

        new GetJSONTask().execute(URI);
    }

    class GetJSONTask extends AsyncTask<String, Integer, String> {

        protected String doInBackground(String... arg0) {

            String uri = arg0[0];

            InputStream is = null;

            if (uri.contains("http") == true) {// Get JSON from URL
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(uri);
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                    BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    while ((line = rd.readLine()) != null) {
                        json += line;
                    }
                    rd.close();
                    return json;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } else {// Get JSON from Assets

                Writer writer = new StringWriter();
                char[] buffer = new char[1024];

                try {
                    InputStream jsonFile = getActivity().getAssets().open(uri);
                    Reader reader = new BufferedReader(new InputStreamReader(jsonFile, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                    jsonFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                json = writer.toString();
                // return JSON String
                return json;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                showData(result);
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "something went wrong", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showData(String json) throws JSONException {
        JSONObject o = new JSONObject(json);
        JSONArray data = o.getJSONArray("results");
    }
}
String json_String=EntityUtils.toString(response.getEntity()); JSONObject temp1=新的JSONObject(json_字符串); 上面的代码将抛出一个异常,看起来应该怪JSON数组括号。但是将JSON数组作为顶级元素是很好的!您只需要使用JSONArray()而不是JSONObject:

String json_string = EntityUtils.toString(response.getEntity()); JSONObject temp1 = new JSONObject(json_string); String json_String=EntityUtils.toString(response.getEntity()); JSONArray temp1=新的JSONArray(json_字符串); 因此,您必须知道在JSON代码中是获得一个JSONArray还是一个作为JSONObject的字典


如果您习惯于iOS/Objective-C JSON解析库,那么它们使用相同的顶级元素来处理JSON字典和JSON数组,因此转到JAVA/Android世界时,我感到困惑的是,根据返回的顶级,有两种处理JSON的类型。

括号表示JSON数组。您应该正确地处理响应。我从php代码中删除了容器数组,它解决了这个问题。Thanks@Johan你能发布你的答案并接受它吗?这样其他人会发现它很有用,并且知道到底是什么解决了这个问题。谢谢@SagarHatekar就可以了,但暂时无法接受。看起来更干净,谢谢你的输入。但是,这个问题与php有关,请参见我上面的评论。
@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Bundle getArgs = this.getArguments();
        String URI = getArgs.getString(KEY_URI);//OR YOU CAN HARD CODE THIS OR GET THE STRING ANYWAY YOU LIKE.

        new GetJSONTask().execute(URI);
    }

    class GetJSONTask extends AsyncTask<String, Integer, String> {

        protected String doInBackground(String... arg0) {

            String uri = arg0[0];

            InputStream is = null;

            if (uri.contains("http") == true) {// Get JSON from URL
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(uri);
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                    BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    while ((line = rd.readLine()) != null) {
                        json += line;
                    }
                    rd.close();
                    return json;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } else {// Get JSON from Assets

                Writer writer = new StringWriter();
                char[] buffer = new char[1024];

                try {
                    InputStream jsonFile = getActivity().getAssets().open(uri);
                    Reader reader = new BufferedReader(new InputStreamReader(jsonFile, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                    jsonFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                json = writer.toString();
                // return JSON String
                return json;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                showData(result);
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "something went wrong", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showData(String json) throws JSONException {
        JSONObject o = new JSONObject(json);
        JSONArray data = o.getJSONArray("results");
    }
}
String json_string = EntityUtils.toString(response.getEntity()); JSONObject temp1 = new JSONObject(json_string); String json_string = EntityUtils.toString(response.getEntity()); JSONArray temp1 = new JSONArray(json_string);