2012-06-20 59 views
22
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://my.server:8080/android/service.php"); 


List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
nameValuePairs.add(new BasicNameValuePair("action", "getjson")); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

HttpResponse response = httpclient.execute(httppost); 

service.php生成一个json字符串。我如何从我的response中获取?顺便说一句,我已经提供了GSON库,我可以使用它的任何方法吗?从HttpResponse获取json

解决方案类似于这个看起来很丑陋,IMO:best way to handle json from httpresponse android

还有很多更好的办法,对不对?

任何帮助表示赞赏,感谢


更新:

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

似乎这样的伎俩。只有一个小问题:字符串被包裹在括号内[]。我应该手动删除它们吗?他们是由PHP生成:■json_encode()

+1

方括号表示一个JSON数组。你应该像这样处理响应。 – Perception

+0

@Perception正确。我从php代码中删除了我的容器数组,并解决了这个问题。谢谢 – Johan

+0

@Johan你可以发布你的答案并接受它,以便其他人可能会发现它有用,并知道究竟是什么解决了问题。谢谢! –

回答

1

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

0

如果我从我的web服务返回JSON字符串,我平时想回一个JSON对象,像这样:

String response = client.getResponse(); 

    if (responseCode == 200) 
    {     
     JSONObject obj = new JSONObject(response);                
    } 
+0

看起来更干净,感谢您的输入。但是,这个问题与php相关,请参阅我上面的评论。 – Johan

1

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

@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"); 
    } 
} 
18

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

 
String json_string = EntityUtils.toString(response.getEntity()); 
JSONObject temp1 = new JSONObject(json_string); 

上面的代码会抛出一个异常,它看起来像JSON数组括号是怪。但是,将JSON数组作为顶级元素是很好的!你只需要使用JSONArray(),而不是把JSONObject:

 
String json_string = EntityUtils.toString(response.getEntity()); 
JSONArray temp1 = new JSONArray(json_string); 

所以你要知道,如果你得到一个JSONArray或单一的字典,是一个JSONObject在你的JSON代码。

如果您习惯于iOS/Objective-C JSON解析库,它们使用相同的顶级元素来处理json字典和json数组,所以转移到JAVA/Android世界让我困惑于有两种类型的处理JSON取决于返回的最高级别。