92

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

这是我当前的 Http get 代码:

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;
}

这是 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();
}

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

4

10 回答 10

73

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

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

JSONObject myObject = new JSONObject(result);
于 2013-08-06T07:23:23.927 回答
13

执行此操作以获取 JSON

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

更多详细信息:从 HttpResponse 获取 json

于 2013-08-06T07:29:33.517 回答
10

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

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");
于 2013-08-06T07:25:49.063 回答
8

如果不查看您的确切 JSON 输出,就很难为您提供一些工作代码。教程非常有用,但您可以使用以下内容:

JSONObject jsonObj = new JSONObject("yourJsonString");

然后,您可以使用以下方法从此 json 对象中检索:

String value = jsonObj.getString("yourKey");
于 2013-08-06T07:24:01.550 回答
3

你需要JSONObject像下面这样使用:

String mJsonString = downloadFileFromInternet(urls[0]);

JSONObject jObject = null;
try {
    jObject = new JSONObject(mJsonString);
} 
catch (JSONException e) {
    e.printStackTrace();
    return false;
}

...

private String downloadFileFromInternet(String url)
{
    if(url == null /*|| url.isEmpty() == true*/)
        new IllegalArgumentException("url is empty/null");
    StringBuilder sb = new StringBuilder();
    InputStream inStream = null;
    try
    {
        url = urlEncode(url);
        URL link = new URL(url);
        inStream = link.openStream();
        int i;
        int total = 0;
        byte[] buffer = new byte[8 * 1024];
        while((i=inStream.read(buffer)) != -1)
        {
            if(total >= (1024 * 1024))
            {
                return "";
            }
            total += i;
            sb.append(new String(buffer,0,i));
        }
    }
    catch(Exception e )
    {
        e.printStackTrace();
        return null;
    }catch(OutOfMemoryError e)
    {
        e.printStackTrace();
        return null;
    }
    return sb.toString();
}

private String urlEncode(String url)
{
    if(url == null /*|| url.isEmpty() == true*/)
        return null;
    url = url.replace("[","");
    url = url.replace("]","");
    url = url.replaceAll(" ","%20");
    return url;
}

希望这可以帮助你..

于 2013-08-06T07:22:40.310 回答
3

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

如果你想要一个JSONObject,那么首先Stringresult

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

然后你可以得到你的JSONObject

JSONObject jsonObject = new JSONObject(jsonString);
于 2020-04-14T15:27:29.830 回答
0

有一个 JSONObject 构造函数可以将 String 转换为 JSONObject:

http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)

于 2013-08-06T07:22:28.190 回答
0

如果您的 api 响应是一个 java 对象,那么您从 Outputstream 获得的字符串应该是 json 字符串格式,例如

{\"name\":\"xyz\", \"age\":21}

. 这可以通过多种方式转换为 JSON 对象,其中一种方法是使用 google GSON 库。 GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); Gson gson = builder.create(); <javaobject> = gson.fromJson(<outputString>, <Classofobject>.class);

于 2021-09-08T07:52:10.430 回答
0

一个人也可以在没有 Gson 的情况下使用实现 Json Tree Model 的 Jackson 来做到这一点。

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(responseString);
于 2021-10-23T03:10:41.830 回答
0

1)String jsonString = EntityUtils.toString(response.getEntity()); 2)JSONObject jsonObject = new JSONObject(jsonString);

于 2022-01-07T10:27:55.400 回答