如何从解析的json数据中解析html?

时间:2014-12-13 14:08:08

标签: java android json jsoup

我尝试从json数据中解析一些url,只从json中的url获取图像并将其显示为图片。但是我不断地从它那里得到错误,而且我不知道如何解决它(是的,我仍然是一个菜鸟)。

我使用here中的代码并稍微更改了json文件和代码。

这是代码

public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();

// Movies json url
static final String url = "http://url";
ProgressDialog pDialog;
List<Movie> movieList = new ArrayList<Movie>();
ListView listView;
CustomListAdapter adapter;

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

    listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, movieList);
    listView.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    // changing action bar color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#1b1b1b")));

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            Movie movie = new Movie();
                            JSONObject obj = response.getJSONObject(i);
                            movie.setTitle(obj.getString("title"));

                            //here where I try to parse the string from json file 
                            String url2= obj.getString("image");
                            Document document = Jsoup.connect(url2).get();
                            Elements img = document.select("div [class=ipsBox] img[src]");
                            String imgSrc = img.attr("src");

                            movie.setThumbnailUrl(imgSrc);

                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);


                            // adding movie to movies array
                            movieList.add(movie);


                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
}


@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}}

这是我使用的json

[{
    "title": "Dawn of the Planet of the Apes",
    "image": "http://bato.to/comic/_/comics/000000-ultra-black-r1425",
    "rating": 8.3,
    "releaseYear": 2014,
    "genre": ["Action", "Drama", "Sci-Fi"]
},
{
    "title": "District 9",
    "image": "http://bato.to/comic/_/comics/g-edition-r886",
    "rating": 8,
    "releaseYear": 2009,
    "genre": ["Action", "Sci-Fi", "Thriller"]
},
{
    "title": "Transformers: Age of Extinction",
    "image": "http://otherurl",
    "rating": 6.3,
    "releaseYear": 2014,
    "genre": ["Action", "Adventure", "Sci-Fi"]
},
{
    "title": "X-Men: Days of Future Past",
    "image": "http://otherurl",
    "rating": 8.4,
    "releaseYear": 2014,
    "genre": ["Action", "Sci-Fi", "Thriller"]
},
{
    "title": "How to Train Your Dragon",
    "image": "http://otherurl",
    "rating": 8.2,
    "releaseYear": 2010,
    "genre": ["Animation", "Adventure", "Family"]
}]

我运行程序后出现错误

我得到的错误

12-13 21:54:55.701: E/AndroidRuntime(28628): FATAL EXCEPTION: main
12-13 21:54:55.701: E/AndroidRuntime(28628): Process: info.androidhive.customlistviewvolley, PID: 28628
12-13 21:54:55.701: E/AndroidRuntime(28628): android.os.NetworkOnMainThreadException
12-13 21:54:55.701: E/AndroidRuntime(28628):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:449)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:434)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:181)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at org.jsoup.helper.HttpConnection.get(HttpConnection.java:170)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at info.androidhive.customlistviewvolley.MainActivity$1.onResponse(MainActivity.java:77)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at info.androidhive.customlistviewvolley.MainActivity$1.onResponse(MainActivity.java:1)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at android.os.Handler.handleCallback(Handler.java:733)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at android.os.Handler.dispatchMessage(Handler.java:95)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at android.os.Looper.loop(Looper.java:136)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at android.app.ActivityThread.main(ActivityThread.java:5146)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at java.lang.reflect.Method.invokeNative(Native Method)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at java.lang.reflect.Method.invoke(Method.java:515)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
12-13 21:54:55.701: E/AndroidRuntime(28628):    at dalvik.system.NativeStart.main(Native Method)

请帮帮我,非常感谢你的回答。

1 个答案:

答案 0 :(得分:0)

根据this answer,我认为在开始解析之前需要这两行:

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);