1

I was a novice at the json parsing from url. yesterday I've tried parsing json simple data. Now I am confused to form a json parsing the data as below. I still can not how to parse arrays and objects in json. Please help me guys ..

here my MainActivity.java

public class MainActivity extends ListActivity {
/** Called when the activity is first created. */

private static String URL = "http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0";

// tag
private static final String TAG_ID = "id";
private static final String TAG_page = "page";
private static final String TAG_results = "results";
private static final String TAG_backdrop_path = "backdrop_path";
private static final String TAG_id = "id";
private static final String TAG_original_title = "original_title";
private static final String TAG_release_date = "release_date";
private static final String TAG_poster_path = "poster_path";
private static final String TAG_title = "title";
private static final String TAG_vote_average = "vote_average";
private static final String TAG_vote_count = "vote_count";
private static final String TAG_total_pages = "total_pages";
private static final String TAG_total_results = "total_results";
JSONArray results = null;
JSONArray id = null;
JSONArray page = null;
JSONArray pages = null;
JSONArray tot_result = null;

// panggil class parser
JSONparser parser = new JSONparser();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ArrayList<HashMap<String, String>> genreList = new ArrayList<HashMap<String, String>>();

    JSONObject json = parser.getJSONFromUrl(URL);
    try {
        id = json.getJSONArray(TAG_ID);
        page = json.getJSONArray(TAG_page);
        pages = json.getJSONArray(TAG_total_pages);
        tot_result = json.getJSONArray(TAG_total_results);

        for (int i = 0; i < results.length(); i++) {
            JSONObject data = results.getJSONObject(i);

            String backdrop = data.getString(TAG_backdrop_path);
            String idd = data.getString(TAG_id).toString();
            String ori = data.getString(TAG_original_title);
            String releas = data.getString(TAG_release_date);
            String poster = data.getString(TAG_poster_path);
            String title = data.getString(TAG_title);
            String average = data.getString(TAG_vote_average);
            String count = data.getString(TAG_vote_count);

            HashMap<String, String> map = new HashMap<String, String>();
            map.put(TAG_backdrop_path, backdrop);
            map.put(TAG_ID, idd);
            map.put(TAG_original_title, ori);
            map.put(TAG_release_date, releas);
            map.put(TAG_poster_path, poster);
            map.put(TAG_title, title);
            map.put(TAG_vote_average, average);
            map.put(TAG_vote_count, count);

            genreList.add(map);
        }

        // Sort by
        /*********************************
         * Collections.sort(genreList, new Comparator<HashMap<String,
         * String>>() {
         * 
         * @Override public int compare(HashMap<String, String> a,
         *           HashMap<String, String> b) { return
         *           a.get(TAG_NAMA).compareTo(b.get(TAG_ID)); } });
         ******************************/

    } catch (JSONException e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    // tampilkan ke listadapter
    ListAdapter adapter = new SimpleAdapter(this, genreList,
            R.layout.list_data, new String[] { TAG_ID, TAG_page,
                    TAG_results, TAG_backdrop_path, TAG_id,
                    TAG_original_title, TAG_release_date, TAG_poster_path,
                    TAG_title, TAG_vote_average, TAG_vote_count,
                    TAG_total_pages, TAG_total_results }, new int[] {
                    R.id.id, R.id.page, R.id.result, R.id.backdrop_path,
                    R.id.idd, R.id.original_title, R.id.release_date,
                    R.id.poster_path, R.id.title, R.id.vote_average,
                    R.id.vote_count, R.id.total_pages, R.id.total_results });
    setListAdapter(adapter);
}
}

here my JSONparser.java

public class JSONparser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONparser() {

}

public JSONObject getJSONFromUrl(String url) {
    // http request
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        // TODO: handle exception
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO: handle exception
        e.printStackTrace();
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 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) {
        // TODO: handle exception
        Log.e("BUffer Error", "Error converting result" + e.toString());
    }

    // try parse string to a json
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        // TODO: handle exception
        Log.e("Json parser", "error parsing data" + e.toString());
    }

    return jObj;

}

}

here my json data.

{
"id": 18,
"page": 1,
"results": [
    {
        "backdrop_path": "/6xKCYgH16UuwEGAyroLU6p8HLIn.jpg",
        "id": 238,
        "original_title": "The Godfather",
        "release_date": "1972-03-24",
        "poster_path": "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg",
        "title": "The Godfather",
        "vote_average": 9.1999999999999993,
        "vote_count": 125
    },
    {
        "backdrop_path": "/ooqPNPS2WdBH7DgIF4em9e0nEld.jpg",
        "id": 857,
        "original_title": "Saving Private Ryan",
        "release_date": "1998-07-24",
        "poster_path": "/35CMz4t7PuUiQqt5h4u5nbrXZlF.jpg",
        "title": "Saving Private Ryan",
        "vote_average": 8.9000000000000004,
        "vote_count": 83
    }
],
"total_pages": 25,
"total_results": 499
}
5
  • 2
    Help you with what? Read a tutorial. Commented Jan 27, 2014 at 3:38
  • I still confuse how to parse array and object json. can you tell me how the right source code to parse? Commented Jan 27, 2014 at 3:41
  • No, giving you source code will not give you anything. Learn what the JSON data types are. Find a json parsing library and learn how to use it to map appropriate types. Commented Jan 27, 2014 at 3:41
  • JSONObject: {}, JSONArray: [] Commented Jan 27, 2014 at 3:43
  • I have try, but no response on emulator. please look my update question. Commented Jan 27, 2014 at 3:44

5 Answers 5

1
JSONObject jObject_Main= new JSONObject(jsonstring);

//get json simple string
String id = jObject_Main.getString("id");
String page = jObject_Main.getString("page");

//get json Array and parse it.
JSONArray jsonArray = jObject_Main
                    .getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
String backdrop_path=jsonObject.getString("backdrop_path");

}

i hope its useful to you.

Sign up to request clarification or add additional context in comments.

7 Comments

if any doubt then tell me.
where the name of my json string?
your json will return some string right?then that string pass in myjsonstring,
you have using soap webservice or httppost?
i confuse what the name of my json string. of my source code above, whice are called json string name? sorry guys, i still beginer ...
|
1

please change this in your code:

 JSONObject json = parser.getJSONFromUrl(URL);
    try {
        id = json.getString("id");
        page = json.getString("page");
      tot_result = json.getJSONArray(results);

i hope you understand it.

Comments

0

Try this..

In your Global:

JSONArray results = null;
String id = null;
String page = null;
String pages = null;
String tot_result = null;

Inside Try Catch:

JSONObject json = parser.getJSONFromUrl(URL);
try {
    id = json.getString(TAG_ID);             // Changes here
    page = json.getString(TAG_page);         // Changes here

    pages = json.getString(TAG_total_pages);  // Changes here

    tot_result = json.getString(TAG_total_results);  // Changes here

    results = json.getJSONArray(TAG_results);       // Add this line

    for (int i = 0; i < results.length(); i++) {
          // Remaining all correct
    }

EDIT:

new DownloadImageTask()
            .execute("your image url");
}

and DownloadImageTask.class

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

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        imageview.setImageBitmap(result);
    }
}

5 Comments

but image og backdrop_pat does not appear
on my json contained the image data, but does not appear. is there any other way to parse image?
@user3197499 is /ooqPNPS2WdBH7DgIF4em9e0nEld.jpg this url for that image
can i get an emage from that url of image?
error "cannot make a static reference to the non-static ... " on protected void onPostExecute(Bitmap results) { ImageView.setImageBitmap(results); }
0

Your JSON is JSONObject and it contains JSONArray

  • Parse Object
  • Parse Array

Example:

JSONObject jsonObj = new JSONObject(your_json_string);

String id = jsonObj.getString("id");
String page = jsonObj.getString("page"); // or getInt("page");

JSONArray results = jsonObj.getJSONArray("results");

int len = results.length(); // length or size, I don't remember, you can check it

for (int i = 0; i < len; i++) {
    JSONObject obj = results.getJSONObject(i);
    String backdropPath = obj.getString("backdrop_path");
    // ...
}

Comments

0

you need add " results= json.getJSONArray(TAG_results);" below "tot_result = json.getJSONArray(TAG_total_results);"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.