Json Array缺少第一个字母?

时间:2018-03-18 17:28:32

标签: java android iptv

我需要从http Get解析和数组。

我收到:

[
  {
    "category_id": "334",
    "category_name": "ENGLISH PREMIER LEAGUE VOD",
    "parent_id": 0
  },......

所以我开始使用

public class Welcome extends Activity {

    Button btnLogout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);



        Intent intent = getIntent();

        String Welcome=("Welcome ," +getIntent().getStringExtra("Username"));
        String Username= (getIntent().getStringExtra("Username"));
        String Password =(getIntent().getStringExtra("Password"));
        TextView textView = (TextView) findViewById(R.id.usertext);
        textView.setTextSize(45);
        textView.setText(Welcome);

          System.out.println("reseived  "+ Welcome);
          System.out.println("reseived Pass  "+ Password);



        btnLogout = (Button) findViewById(R.id.btnLogout);

        btnLogout.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                Intent login = new Intent(getApplicationContext(), MainActivity.class);
                login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(login);
                finish();

                System.exit(0);

            }
        });
        new DownloadTask().execute("http://stb.spades-tv.xyz:25461/player_api.php?username=" + Username + "&password=" + Password+"&action=get_vod_categories");

    }

Andthen

private class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        try {
            return downloadContent(params[0]);
        } catch (IOException e) {
            return "Unable to retrieve data. URL may be invalid.";
        }
    }

    @Override
    protected void onPostExecute(String result) {

        Toast.makeText(Welcome.this, result, Toast.LENGTH_LONG).show();
    }
}
    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));

        String line = "";
        Reader reader = null;

        String result = "";
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[length];
        reader.read(buffer);

        while ((line = bufferedReader.readLine()) != null)
            result += line;

        stream.close();
        if (result != null) {

//TODO someting here 
        }
        else { System.out.println(" 404 "); }

        getinfos(result);
        return result;


       // return new String(buffer);
    }
    private String downloadContent(String myurl) throws IOException {



        InputStream is = null;
        int length = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(TAG, "The response is: " + response);

            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = convertInputStreamToString(is, length);

             System.out.println("Received from VOD list :" + contentAsString);

            return contentAsString;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

在这部分我想转换为数组

[]数组和{}对象对吗?

   public void getinfos (String  result)
    {

        try {


            JSONArray jsonArr = new JSONArray(result);

            for (int i = 0; i < jsonArr.length(); i++)
            {
                JSONObject jsonObj = jsonArr.getJSONObject(i);

         System.out.println(" My VOD List :" +jsonObj);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

奇怪的是,这看到第一个atergory_id我缺少了一部分吗?我收到这个错误?:

W/System.err: org.json.JSONException: Value egory_id" of type java.lang.String cannot be converted to JSONArray
W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err:     at ca.iptvbooster.testhttp.Welcome.getinfos(Welcome.java:185)
W/System.err:     at ca.iptvbooster.testhttp.Welcome.convertInputStreamToString(Welcome.java:129)
W/System.err:     at ca.iptvbooster.testhttp.Welcome.downloadContent(Welcome.java:156)
W/System.err:     at ca.iptvbooster.testhttp.Welcome.access$100(Welcome.java:41)
W/System.err:     at ca.iptvbooster.testhttp.Welcome$DownloadTask.doInBackground(Welcome.java:95)
W/System.err:     at ca.iptvbooster.testhttp.Welcome$DownloadTask.doInBackground(Welcome.java:89)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err:     at java.lang.Thread.run(Thread.java:764)
I/System.out: Received from VOD list :egory_id":"195","category_name":"LINE OF DUTY SEASON 2","parent_id":"77"},..

1 个答案:

答案 0 :(得分:0)

演示清理版本的'convertInputStreamToString',它是解析问题的根源 - 请参阅注释。包含测试代码。 “getinfos”在编码时起作用了。

  import android.util.Log;
  import org.json.*;
  import java.io.*;
  import java.nio.charset.Charset;

  public class TestJsonParse {

      public void test() {
          StringBuffer sb = new StringBuffer();
          sb.append("[ { 'category_id': '334', 'category_name': 'ENGLISH PREMIER LEAGUE VOD', 'parent_id': 0 }, ");
          sb.append("{ 'category_id': '456', 'category_name': 'ENGLISH PREMIER LEAGUE ROCKS', 'parent_id': 2 }]");
          InputStream stream = new ByteArrayInputStream(sb.toString().getBytes(Charset.forName("UTF-8")));
          try {
              convertInputStreamToString(stream);
          } catch (Exception e) {
              Log.e("TestJsonParse", "Issue with stream: "+e);
          }
      }

      /** @return null if errors reading/parsing stream. */
      public String convertInputStreamToString(InputStream stream) throws IOException {

          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
          StringBuffer sb = new StringBuffer();
          String result = null;
          String line;
          while ((line = bufferedReader.readLine()) != null) {
              sb.append(line);
          }
          //https://stackoverflow.com/questions/1388602/do-i-need-to-close-both-filereader-and-bufferedreader
          bufferedReader.close();

          if (sb.length() > 0) {
              result = sb.toString();
              getinfos(result);
          }
          else {
              Log.e("TestJsonParse"," 404 ");
          }

          return result;
      }


      // Existing 'getinfos' worked as is...
   }