从HTTP响应中获取JSON对象

Zap*_*ica 64 java android json

我想JSON从Http get响应中获取一个对象:

这是我目前的Http获取代码:

protected String doInBackground(String... params) {

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(params[0]);
    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();
            if (response.getStatusLine().getStatusCode() == 200) {
                netState.setLogginDone(true);
            }

        }
        // Headers
        org.apache.http.Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

这是convertSteamToString函数:

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();
}
Run Code Online (Sandbox Code Playgroud)

现在我只是得到一个字符串对象.如何获取JSON对象.

Ren*_*ira 60

您获得的字符串只是JSON Object.toString().这意味着您获得了JSON对象,但是采用String格式.

如果你应该得到一个JSON对象,你可以放:

JSONObject myObject = new JSONObject(result);
Run Code Online (Sandbox Code Playgroud)


roc*_*tar 10

这样做是为了获得JSON

String json = EntityUtils.toString(response.getEntity());
Run Code Online (Sandbox Code Playgroud)

更多细节在这里:从HttpResponse获取json

  • 那是*String*而不是JSON! (25认同)
  • 为什么会有这么多的赞成?这只是一个`toString()`函数 - 基本上与OP完全相同. (5认同)
  • 请开始downvoting,因为这是不正确的 (4认同)

Joe*_*rch 8

如果不看你确切的JSON输出,很难给你一些工作代码.教程非常有用,但您可以使用以下内容:

JSONObject jsonObj = new JSONObject("yourJsonString");
Run Code Online (Sandbox Code Playgroud)

然后你可以使用以下方法从这个json对象中检索:

String value = jsonObj.getString("yourKey");
Run Code Online (Sandbox Code Playgroud)


Sar*_*san 7

这不是您问题的确切答案,但这可能对您有所帮助

public class JsonParser {

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<Club> getNearestClubs(double lat, double lon) {
        // YOUR URL GOES HERE
        String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);

        List<Club> ret = new ArrayList<Club>();

        HttpResponse response = null;
        HttpGet getMethod = new HttpGet(getUrl);
        try {
            response = httpClient.execute(getMethod);

            // CONVERT RESPONSE TO STRING
            String result = EntityUtils.toString(response.getEntity());

            // CONVERT RESPONSE STRING TO JSON ARRAY
            JSONArray ja = new JSONArray(result);

            // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
            int n = ja.length();
            for (int i = 0; i < n; i++) {
                // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                JSONObject jo = ja.getJSONObject(i);

                // RETRIEVE EACH JSON OBJECT'S FIELDS
                long id = jo.getLong("id");
                String name = jo.getString("name");
                String address = jo.getString("address");
                String country = jo.getString("country");
                String zip = jo.getString("zip");
                double clat = jo.getDouble("lat");
                double clon = jo.getDouble("lon");
                String url = jo.getString("url");
                String number = jo.getString("number");

                // CONVERT DATA FIELDS TO CLUB OBJECT
                Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
                ret.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // RETURN LIST OF CLUBS
        return ret;
    }

}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:

JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");
Run Code Online (Sandbox Code Playgroud)


Cat*_*rvu 6

为了彻底解决这个问题(是的,我知道这篇文章很久以前就死了......):

如果你想要一个JSONObject,那么首先String从以下位置获取一个result

String jsonString = EntityUtils.toString(response.getEntity());
Run Code Online (Sandbox Code Playgroud)

然后你可以得到你的JSONObject

JSONObject jsonObject = new JSONObject(jsonString);
Run Code Online (Sandbox Code Playgroud)