Android JSON 解析 - 错误字符 0 处的输入结束 [英] Android JSON Parsing - End of input at character 0 of error

查看:24
本文介绍了Android JSON 解析 - 错误字符 0 处的输入结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次制作解析 JSON 数据的 android 应用程序.但是,我遇到了有关 JSON 解析的错误.我试过谷歌搜索这个问题,但大多数解决方案对我不起作用.

This is my first time making an android application that parses JSON data. However, I'm encountering an error regarding JSON parsing. I've tried Googling the problem but most of the solutions didn't work for me.

这是我的代码:

MainActivity.java

package com.example.jsonparser;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://pastebin.com/raw/79D93HR4";

    ArrayList<HashMap<String, String>> itemList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        itemList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetItems().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetItems extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    //JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray items = new JSONArray("");

                    // looping through All Contacts
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject c = items.getJSONObject(i);

                        String ItemCode = c.getString("ItemCode");
                        String ItemName = c.getString("ItemName");

                        // tmp hash map for single item
                        HashMap<String, String> item = new HashMap<>();

                        // adding each child node to HashMap key => value
                        item.put("ItemCode", ItemCode);
                        item.put("ItemName", ItemName);

                        // adding item to item list
                        itemList.add(item);
                    }

                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, itemList,
                    R.layout.list_item, new String[]{"ItemCode", "ItemName"}, new int[]{R.id.ItemCode,
                    R.id.ItemName});

            lv.setAdapter(adapter);
        }

    }
}

HttpHandler.java

package com.example.jsonparser;

/**
 * Created by Me on 1/3/2017.
 */
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

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 (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        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();
            }
        }
        return sb.toString();
    }
}

这是错误代码:

01-04 00:13:05.366 10069-10112/com.example.jsonparser E/MainActivity: Response from url: [{"ItemCode":"C0100001  ","ItemName":"UBNT CRM-P-CRM Point","LocationCode":null,"ViewBy":null,"SearchDate":null,"CutOffDate":"\/Date(-62135596800000)\/","CurrentDate":"\/Date(-62135596800000)\/"},{"ItemCode":"C0100002  ","ItemName":"UBNT ETH-SP-Ethernet Surge Protector","LocationCode":null,"ViewBy":null,"SearchDate":null,"CutOffDate":"\/Date(-62135596800000)\/","CurrentDate":"\/Date(-62135596800000)\/"}]
01-04 00:13:05.367 10069-10112/com.example.jsonparser E/MainActivity: Json parsing error: End of input at character 0 of 

我做错了什么?

推荐答案

JSONArray 需要一个 json 字符串.在 JSONArray 初始化

JSONArray need a json string. Pass your json in JSONArray initialize

JSONArray items = new JSONArray(jsonStr );

这篇关于Android JSON 解析 - 错误字符 0 处的输入结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆