从url解析Android中的JSON

时间:2015-11-21 10:59:55

标签: android json parsing

我正在创建一个应用程序,我必须从url =“http://www.omdbapi.com/?t=drishyam”解析以下JSON

JSON是:

{"Title":"Drishyam","Year":"2015","Rated":"N/A","Released":"31 Jul 2015","Runtime":"163 min","Genre":"Drama, Mystery, Thriller","Director":"Nishikant Kamat","Writer":"Jeethu Joseph (original story), Upendra Sidhaye (adapted by)","Actors":"Ajay Devgn, Shriya Saran, Tabu, Rajat Kapoor","Plot":"Desperate measures are taken by a man who tries to save his family from the dark side of the law, after they commit an unexpected crime.","Language":"Hindi","Country":"India","Awards":"N/A","Poster":"http://ia.media-imdb.com/images/M/MV5BMTYyMjgyNDY3N15BMl5BanBnXkFtZTgwOTMzNTE5NTE@._V1_SX300.jpg","Metascore":"N/A","imdbRating":"8.9","imdbVotes":"16,509","imdbID":"tt4430212","Type":"movie","Response":"True"}

MainActivity.java

 private class GetContacts extends AsyncTask<String, Void, Bitmap> {

        @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 Bitmap doInBackground(String... abc) {
            html = new Parsing();

            html.JsonParse(url);

            contactList = new ArrayList<LinkedHashMap<String, String>>();
            contactList.clear();

            contactList=html.contactList;
            System.out.println("Size od cintactlist in Main " + contactList.size());

            int c=0;
            for (LinkedHashMap<String, String> map : contactList) {
                for (Map.Entry<String, String> mapEntry : map.entrySet()) {
                    if (c == 0) {
                        String key = mapEntry.getKey();
                        String value = mapEntry.getValue();
                        if(!key.equals("poster"))
                        ans="key "+" is "+value+"\n\n";
                        else
                            poster=value;
                        System.out.println("Value of key and value is " + key + "  " + value);
                    } else
                        break;
                }
                c++;
            }

            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(poster).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
//                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;

        }

        @Override
        protected void onPostExecute(Bitmap result) {

            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            lbName.setText(ans);
            imgview.setImageBitmap(result);
//            lblEmail.setText(ans);
        }

    }

Parsing.java

package com.movie.comparemovie;

import android.content.Context;
import android.util.Log;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.LinkedHashMap;

public class Parsing {

    Context context;

    ArrayList<LinkedHashMap<String, String>> contactList;

    public void JsonParse(String URL1) {
        contactList = new ArrayList<LinkedHashMap<String, String>>();

        String logoLink = null;
        try {

            // instantiate our json parser
            JsonParser jParser = new JsonParser();

            JSONObject json = jParser.getJSONFromUrl(URL1);

                String Title = json.getString("Title");
                System.out.println("Title is "+Title);
                String tab1_text = json.getString("tab1_text");
                int active = json.getInt("active");


            System.out.println("Movie Title is :" + Title);
//          // Storing each json item in variable
//          String year = json1.getString("Year");
//          String released = json1.getString("Released");
//          String runtime = json1.getString("Runtime");
//          String poster = json1.getString("Poster");

            LinkedHashMap<String, String> value = new LinkedHashMap<String, String>();

            value.put("title", Title);
//          value.put("Year", year);
//          value.put("Runtime", runtime);
//          value.put("Poster", poster);

            contactList.add(value);
//              System.out.println("Size od cintactlist in Prasing " + contactList.size());


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

    }

    public class JsonParser {

        final String TAG = "JsonParser.java";

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

        public JSONObject getJSONFromUrl(String ul) {
            System.out.println("Inside jsonparser class");

            try {
                URL url = new URL(ul);
                URLConnection connection = url.openConnection();
                //connection.addRequestProperty("Referer", "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%22mixorg.com%22&rsz=8");

                String line;
                StringBuilder builder = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                    System.out.println(builder.toString());
                }
                json = builder.toString();

            } catch (Exception e) {
                Log.e(TAG, "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e(TAG, "Error parsing json data " + e.toString());
            } catch (Exception e) {

            }
            // return JSON String
            return jObj;
        }
    }
}

其中JsonParser是一个类,getJSONfromURL返回jsonobject。 但它不会工作。 我该如何解析这个JSON?

3 个答案:

答案 0 :(得分:0)

试试这个:

try {
            JSONObject json = new JSONObject("Your String");
            String title = json.getString("Title");
            String year = json.getString("Year");
            //get your all other keys just like title and year
        } catch (JSONException e) {
            e.printStackTrace();
        } 

答案 1 :(得分:0)

首先从链接获取Xml代码,然后使用XMLpullparser解析控制台中的resul_xml代码.Xmlpullparser提供内置方法来存储单个json对象或多个json对象,如果你在同一个链接中有很多电影(url) =&#34; HTTP://www.omdbapi.com/)

答案 2 :(得分:-1)

这样做,

public class getData extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading category....");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String response = null;
        try {
            URL url = new URL("http://www.omdbapi.com/?t=drishyam");
            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            conn.setRequestMethod("GET");
            System.out.println("Response Code: " + conn.getResponseCode());
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = IOUtils.toString(in, "UTF-8");
            System.out.println(response);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result != null) {
            try {

                JSONObject c = new JSONObject(result);
                String Title = c.getString("Title");
                String Year = c.getString("Year");
                String Rated = c.getString("Rated");
                String Released = c.getString("Released");
                String Runtime = c.getString("Runtime");
                String Genre = c.getString("Genre");
                String Genre = c.getString("Genre");
                String Writer = c.getString("Writer");
                String Actors = c.getString("Actors");
                String Plot = c.getString("Plot");
                String Language = c.getString("Language");
                String Country = c.getString("Country");
                String Awards = c.getString("Awards");
                String Poster = c.getString("Poster");
                String Metascore = c.getString("Metascore");
                String imdbRating = c.getString("imdbRating");
                String imdbVotes = c.getString("imdbVotes");
                String imdbID = c.getString("imdbID");
                String Type = c.getString("Type");
                String Response = c.getString("Response");

                Log.e("", "TAG : - " + id);

            } catch (Exception e) {
                Log.e("", "Home Exception : " + e.toString());
            }
        }
        pDialog.dismiss();

        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                ListView.setAdapter(
                        new MenuAdapter(getActivity(), arrayList, 0));
            }
        });
    }
}

快乐的编码,乐意帮助.....