无法解析Twitter趋势JSON

时间:2013-04-04 07:21:18

标签: android json twitter

我正在[blog]:http://www.androidhive.info/2012/01/android-json-parsing-tutorial/的帮助来解析Twitter趋势JSON文件,但它会抛出JSONException。以下是我的活动代码

import java.util.ArrayList;

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

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class TweeterJSONReader extends Activity {

    Button click;
    ListView resultList;
    EditText input;
    JSONAdapter myAdapter;
    ArrayList<SearchResult> mainList;
    JSONParser jParser;

    private String url ="https://api.twitter.com/1/trends/daily.json";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setLayout();

        jParser = new JSONParser();




    click.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    new JSONAsync().execute(url);
                }
            });
    }

    private class JSONAsync extends AsyncTask<String, Void, JSONObject>
    {

        JSONArray trends;
        @Override
        protected JSONObject doInBackground(String... params) {

            return jParser.getJSONFromUrl(params[0]);
        }

        @Override
        protected void onPostExecute(JSONObject result) {

            try{
                trends  = result.getJSONArray("trends");

                for(int i=0;i<trends.length();i++)
                {
                    JSONObject trend = trends.getJSONObject(i);
                    String name = trend.getString("name");
                    String query  = trend.getString("query");
                    SearchResult object  = new SearchResult(name, query);
                    mainList.add(object);
                    myAdapter  = new JSONAdapter(getApplicationContext(),R.layout.search_result_layout,mainList);
                    resultList.setAdapter(myAdapter);
                }
            }catch(JSONException ex)
            {
                ex.printStackTrace();
            }
        }

    }
    public void setLayout()
     {
         mainList = new ArrayList<SearchResult>();
         click = (Button) findViewById(R.id.display);
         resultList = (ListView) findViewById(R.id.resultList);

        input = (EditText) findViewById(R.id.editText1);

     }
}

我使用相同的东西通过哈希标记和用户名搜索推文它们都工作正常但是当我将它用于趋势时它会抛出JSONException 以下是我得到的例外

04-04 12:09:25.919: W/ResponseProcessCookies(620): Invalid cookie header: "set-cookie: guest_id=v1%3A136505757287468464; Domain=.twitter.com; Path=/; Expires=Sat, 04-Apr-2015 06:39:32 UTC". Unable to parse expires attribute: Sat, 04-Apr-2015 06:39:32 UTC
04-04 12:09:25.950: W/System.err(620): org.json.JSONException: No value for trends
04-04 12:09:25.950: W/System.err(620):  at org.json.JSONObject.get(JSONObject.java:354)
04-04 12:09:25.950: W/System.err(620):  at org.json.JSONObject.getJSONArray(JSONObject.java:544)
04-04 12:09:25.969: W/System.err(620):  at com.zolipe.twitterapplication.TweeterJSONReader$JSONAsync.onPostExecute(TweeterJSONReader.java:63)
04-04 12:09:25.969: W/System.err(620):  at com.zolipe.twitterapplication.TweeterJSONReader$JSONAsync.onPostExecute(TweeterJSONReader.java:1)
04-04 12:09:25.969: W/System.err(620):  at android.os.AsyncTask.finish(AsyncTask.java:417)
04-04 12:09:25.969: W/System.err(620):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
04-04 12:09:25.969: W/System.err(620):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
04-04 12:09:25.969: W/System.err(620):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 12:09:25.980: W/System.err(620):  at android.os.Looper.loop(Looper.java:123)
04-04 12:09:25.992: W/System.err(620):  at android.app.ActivityThread.main(ActivityThread.java:3683)
04-04 12:09:25.992: W/System.err(620):  at java.lang.reflect.Method.invokeNative(Native Method)
04-04 12:09:25.992: W/System.err(620):  at java.lang.reflect.Method.invoke(Method.java:507)
04-04 12:09:25.992: W/System.err(620):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-04 12:09:25.999: W/System.err(620):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-04 12:09:25.999: W/System.err(620):  at dalvik.system.NativeStart.main(Native Method)
04-04 12:09:28.470: D/dalvikvm(121): GC_EXPLICIT freed 126K, 49% free 3050K/5959K, external 3611K/4459K, paused 100ms

请帮帮我

以下是JSONParser的代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            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;

    }
}

1 个答案:

答案 0 :(得分:1)

如果您转到https://api.twitter.com/1/trends/daily.json,您会看到trends实际上是JSONObject,而不是JSONArray

trends更改为JSONObject类型的对象,并更改此行:

trends  = result.getJSONArray("trends");

到此:

trends  = result.getJSONObject("trends");

此外,您正在寻找所有趋势的JSONArray实际上包含在另一个JSONObject中,日期为关键字,因此您需要再添加一个步骤(之后)上面的那个):

JSONArray trendArry = trends.getJSONArray("2013-04-03 08:20");