Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm parsing this document: http://pastebin.com/M3Gsbf1t as you can see it's kind of big. This document was generated by Youtube Data API v3. I want to get all "title" elements and display them. My code:

Object obj = parser.parse(str); // str contains the JSON code
JSONObject jsonObject = (JSONObject) obj;               
JSONArray msg = (JSONArray) jsonObject.get("title");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
  System.out.println(iterator.next());
}

but it returns "NullPointerException". If I replace the "title" with the "items" it works fine but it returns me a lot of informations that I don't need. I'm using the JSON.simple library.

Thanks for help :)

share|improve this question
    
title is not at the root of the JSON. You need to traverse the JSON object tree to get it. Also, where is title a JSONArray? –  Sotirios Delimanolis Nov 25 '13 at 21:49

3 Answers 3

up vote 1 down vote accepted

This code should work:

    JSONObject jsonObject = (JSONObject) obj;               
    JSONArray msg = (JSONArray) jsonObject.get("items");
    Iterator iterator = msg.iterator();
    while (iterator.hasNext()) {
      //System.out.println(iterator.next());
      JSONObject item = (JSONObject) iterator.next();
      JSONObject item_snippet = (JSONObject) item.get("snippet");
      System.out.println( item_snippet.get("title"));
    }

You have a JSONObject at the root of your JSON string. In it, there's an JSONArray named items. From it you have to pull out individual items in while loop.

For each item there's JSONObject snippet nested in. Finally you'll find your title string in it.

share|improve this answer
    
Works. Thanks for help again ;) –  PoQ Nov 26 '13 at 13:01

jquery solution, this should give you an array of titles unless I am reading the object wrong.

  titles = [];
  obj = $.parseJSON(str);
  $.each(obj.items,function(i,v{
     titles.push(v.snippet.title);
  });
share|improve this answer

Should be something like this:

Object obj = parser.parse(str); // str contains the JSON code
JSONObject jsonObject = (JSONObject) obj;               
JSONArray msg = (JSONArray) jsonObject.get("items");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
  // cast next item to JSONObject
  JSONObject item = (JSONObject) iterator.next();
  // grab the title
  System.out.println(item.get("title"));
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.