简体   繁体   中英

Parsing JSON in Android from url

I am making an App in which i have to parse the following JSON from the url="http://www.omdbapi.com/?t=drishyam"

JSON is :

{"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;
        }
    }
}

where JsonParser is a class and getJSONfromURL returns jsonobject. But it wont work. How can i parse this JSON ?

Try this :

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();
        } 

首先从链接中获取 Xml 代码,然后使用 XMLpullparser 解析控制台中的 results_xml 代码。Xmlpullparser 提供内置方法以存储在单个 json 对象或多个 json 对象中,如果您在同一链接中有许多电影(url="http ://www.omdbapi.com/)

Do like that,

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));
            }
        });
    }
}

Happy Coding and Happy To Help.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM