2013-11-23 2 views
0

Хорошо, я получил HTTP/1.1 200 OK из ресурса application/json.Как конвертировать приложение/json-ответ в JSONObject?

HttpClient client = new DefaultHttpClient(); 
HttpGet request = new HttpGet("http://www.my bla bla bla web dot com"); 
HttpResponse response = client.execute(request); 

Это ответ:

HTTP/1.0 200 OK 
Cache-Control: no-cache 
Content-Type: application/json 
Date:   Sat, 23 Nov 2013 21:33:47 GMT 

{ 
    "itemCount":2, 
    "items":[{ 
     "datetime":"2013-11-23 22:23:35", 
     "foods":["Spaghetti","Pizza"] 
    },{ 
     "datetime":"2013-11-23 22:23:34", 
     "foods":["Pizza","Pasta","Parmigiano Reggiano"] 
    }] 
} 

Как я могу преобразовать это JSONObject?

ответ

0

Используя эту баночку http://www.json.org/java/

с помощью этого метода для синтаксического анализа потока:

private static String convertStreamToString(InputStream is) { 

    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 

Затем реализовать метод для разбора HTTP которым возвращает строку вы нужду, как так:

HttpResponse response; 
    String result = null; 
    try { 
     response = client.execute(request);   
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 

      // A Simple JSON Response Read 
      InputStream instream = entity.getContent(); 
      result = convertStreamToString(instream); 
      // now you have the string representation of the HTML request 
      System.out.println("RESPONSE: " + result); 
      instream.close(); 

     } 

    } catch (ClientProtocolException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    return result; 

и наконец:

JSONObject obj = new JSONObject(result); 

Позвольте мне теперь, если это ясно!

+0

Rensponse, не является JSON. Выполняется ответчик HTTP. Первые 5 строк не JSON. – sensorario

+1

Я сделаю лучший ответ ... всего секунду. –

0
private class GetTask extends 
     AsyncTask<String, Void, JSONItems> { 
    @Override 
    protected JSONItems doInBackground(String... uri) { 
     JSONItems result = new JSONItems(); 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpResponse response; 
     HttpGet request = new HttpGet(uri[0]); 

     String responseString = null; 

     try { 
      response = httpClient.execute(request); 
      StatusLine statusLine = response.getStatusLine(); 
      if (statusLine.getStatusCode() == HttpStatus.SC_OK) { 
       ByteArrayOutputStream out = new ByteArrayOutputStream(); 
       response.getEntity().writeTo(out); 
       out.close(); 
       responseString = out.toString(); 
       JSONObject jSonObject = new JSONObject(responseString); 
       JSONArray jSonArray = jSonObject 
         .getJSONArray("items"); 
       if (jSonArray.length() > 0) { 
        for (int j = 0; j < jSonArray.length(); j++) { 
         result = convertJSONItems(jSonArray 
           .getJSONObject(j)); 
        } 
        return result; 
       } 
      } else { 
       // Closes the connection. 
       response.getEntity().getContent().close(); 
       throw new IOException(statusLine.getReasonPhrase()); 
      } 
     } catch (ClientProtocolException e) { 
      // TODO Handle problems.. 
     } catch (IOException e) { 
      // TODO Handle problems.. 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(JSONItems result) { 
     if (result != null) { 
        //TODO : Do what you want to do .. 
     } 
    } 

    @Override 
    protected void onCancelled(JSONItems result) { 

    } 

    private JSONItems convertJSONItems(JSONObject obj) 
      throws JSONException { 
     JSONItems item = new JSONItems(); 
     item.datetime = obj.getString("datetime"); 
     item.foods = obj.getString("foods"); 
     return item; 
    } 
} 
+0

Его возможности JSONItems не существует? – sensorario

+0

Вам нужно создать объект JSONItems Создать новый класс как имя JSONItems public class JSONItems { public String datetime; общественные стручковые продукты; } Он будет работать – zapdroid

Смежные вопросы