没有收到完整的JSON

时间:2018-01-05 07:01:33

标签: android json url request fragment

在获取JSON的阶段,所有数据的一部分出现,并且在日志错误中:

无法转换为JSONArray

我看了类似的问题,没找到我需要的答案,谢谢

URL = "http://legs-legs.ru/cat1json.php?json=cat1";
...
HttpHandler sh = new HttpHandler();
            String jsonStr = sh.makeServiceCall(url);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (url != null) {
                try {
                    JSONArray array = new JSONArray(url);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject c = null;
                        c = array.getJSONObject(i);

                        String id = c.getString("id");

请求:

Log.e(TAG,响应)给了我不受欢迎的字符串

    public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) 
            url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch ...
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new 
    InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.e(TAG,sb.toString());
        return sb.toString();
    }
}

3 个答案:

答案 0 :(得分:2)

  

无法转换为JSONArray

因为您的JSON respose字符串错误 jsonStr 而非 url 更改

使用此

 URL = "http://legs-legs.ru/cat1json.php?json=cat1";
 String jsonStr = sh.makeServiceCall(url);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (url != null) {
                try {
                    JSONArray array = new JSONArray(jsonStr);
                    // json parsing code

而不是这个

 URL = "http://legs-legs.ru/cat1json.php?json=cat1";
 String jsonStr = sh.makeServiceCall(url);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (url != null) {
                try {
                    JSONArray array = new JSONArray(url);

答案 1 :(得分:0)

将此行更改为 - :

JSONArray array = new JSONArray(url);

要 - :

String jsonStr = sh.makeServiceCall(url);
JSONArray array = new JSONArray(jsonStr);

答案 2 :(得分:0)

替换它 JSONArray array = new JSONArray(url); 有: JSONArray array = new JSONArray(jsonStr);

jsonStr构造函数中传递JSONArray()而不是url