在Android中解析JSON数组时出错

时间:2017-01-14 16:00:27

标签: android json

我正在尝试从网站中提取数据并在我的Android应用中显示图表。我哪里弄错了?它无法解析JSON。我经历了一些链接,但无法解决问题。

请说明我可以在这两个方面做些什么改变。

  1. 如何在视图[第126行]
  2. 中设置值
  3. 我是否以正确的方式声明了ListView [第118行] 我在代码中标记了这些行。请参阅。提前致谢
  4. 我得到的错误被粘贴

    JSON Parser: Error parsing data org.json.JSONException: Expected ':'
    after n at character 5 of {n  "status": "ok",n  "name": "Transaction
    Rate",n  "unit": "Transactions Per Second",n  "period": "minute",n 
    "description": "The number of Bitcoin transactions added to the
    mempool per second.",n  "values": [n    {n      "x": 1481383260,n     
    "y": 3.060833333333333n    },n    {n      "x": 1481385240,n      "y":
    3.0708333333333324n    },n    {n      "x": 1481387220,n      "y":
    

    MainActivity.Java

    package com.example.garima.bitcoingraph;
    
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import org.w3c.dom.Text;
    
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.TextView;
    
    import java.util.List;
    
    import garima.asynctask.library.JSONParser;
    
    public class MainActivity extends AppCompatActivity {
        TextView status;
        TextView name;
        TextView unit;
        TextView period;
        TextView description;
        ListView value;
    
        Button Btngetdata;
    
        //URL to get JSON Array
        private static String url = "https://api.blockchain.info/charts/transactions-per-second?timespan=5weeks&rollingAverage=8hours&format=json";
    
        //JSON Node Names
        private static final String TAG_STATUS = "status";
        private static final String TAG_NAME = "name";
        private static final String TAG_UNIT = "unit";
        private static final String TAG_PERIOD = "period";
        private static final String TAG_DESCRIPTION="description";
        private static final String TAG_USER="user";
        private static final String TAG_VALUE="value";
        private static final String TAG = "MyActivity";
        JSONArray user = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
            Btngetdata = (Button)findViewById(R.id.getdata);
            Btngetdata.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View view) {
                    new JSONParse().execute();
    
                }
            });
    
        }
    
        private class JSONParse extends AsyncTask<String, String, JSONObject> {
            private ProgressDialog pDialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                status = (TextView)findViewById(R.id.status);
                name = (TextView)findViewById(R.id.name);
                unit = (TextView)findViewById(R.id.unit);
                period=(TextView)findViewById(R.id.period);
                description=(TextView)findViewById(R.id.description);
                value=(ListView)findViewById(R.id.value);
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Getting Data ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
    
            }
    
            @Override
            protected JSONObject doInBackground(String... args) {
                JSONParser jParser = new JSONParser();
    
                // Getting JSON from URL
                JSONObject json = jParser.getJSONFromUrl(url);
                Log.i(TAG,"json found is"+json);
                return json;
            }
    
            @Override
            protected void onPostExecute(JSONObject json) {
                pDialog.dismiss();
                Log.i(TAG,"json is"+json);
                try {
    
                    // Getting JSON Array<Discuss how to get values>
                   user = json.getJSONArray(TAG_USER);
                   JSONObject c = user.getJSONObject(0);
    
                    // Storing  JSON item in a Variable
                    String Status_Value = c.getString(TAG_STATUS);
                    String Name_Value = c.getString(TAG_NAME);
                    String Unit_Value = c.getString(TAG_UNIT);
                    String Period_Value=c.getString(TAG_PERIOD);
                    String Description_Value=c.getString(TAG_DESCRIPTION);
                    List Values_Value=c.getClass(TAG_VALUE); //118
    
                    //Set JSON Data in TextView
                    status.setText(Status_Value);
                    name.setText(Name_Value);
                    unit.setText(Unit_Value);
                    period.setText(Period_Value);
                    description.setText(Description_Value);
                    ->How to set values for Values?//126
    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
    
            }
        }
    
    }
    

    JSON:

       {   "status": "ok",  
           "name": "Transaction Rate",  
           "unit":"Transactions Per Second",   
           "period": "minute",  
           "description": "The number of Bitcoin transactions added to the mempool per second.",  
          "values": [
              {
                "x": 1481385360,
                "y": 3.069444444444444
              },
              {
                "x": 1481387340,
                "y": 3.0919444444444437
              },
              {
                "x": 1481389320,
                "y": 3.144861111111111
              } 
          ]
      }
    

    添加getJSONfromURL方法

     public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
    
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    

2 个答案:

答案 0 :(得分:2)

更改,

while ((line = reader.readLine()) != null) {
    sb.append(line + "n");
}

要,

while ((line = reader.readLine()) != null) {
    sb.append(line);
}

您必须打算撰写\n,但忘记撰写\。这是n中迷路JSON字符的来源。

现在您可以使用POJO类和GSON库来解析JSON

答案 1 :(得分:1)

Error parsing data org.json.JSONException: Expected ':'
> after n at character 5 of {n  "status": 

你的json中有一个流浪角色。摆脱n。