I am trying to create android app that shows details about the restaurants. I have parseJSON function which takes string json as an argument. What I am trying to do for now is to show name of individual restaurants in the json below. I am able to extract individual restaurant(3 levels deep) and print them out through log.d console but I am not able to extract out the individual restaurant's name. Here is the code
public void parseJSON(String jsonQuery){
//Parsing JSON
try {
JSONObject jsonObject = new JSONObject(jsonQuery);
if (jsonObject != null){
JSONArray restaurants = jsonObject.getJSONArray("restaurants");
for (int i = 0; i < restaurants.length(); i++){
JSONObject restaurant = restaurants.getJSONObject(i);
if (restaurant != null){
String tempName = restaurant.getString("name");
Log.d(TAG, "Restaurant name: " + tempName);
}
}
}
} catch (JSONException e) {
Log.d(TAG, "Exception catched: " + e);
e.printStackTrace();
}
}
Here is my json file.
{
"results_found": 1281966,
"results_start": 0,
"results_shown": 2,
"restaurants": [
{
"restaurant": {
"R": {
"res_id": 16607974
},
"apikey": "123456789",
"id": "16607974",
"name": "Bassine Specialty Cheese",
"url": "https://www.zomato.com/bass-vic/bassine-specialty-cheese-bass?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "2125 Bass Hwy",
"locality": "Bass",
"city": "Bass",
"city_id": 1341,
"latitude": "-38.4833750000",
"longitude": "145.4670320000",
"zipcode": "3995",
"country_id": 14,
"locality_verbose": "Bass, Bass"
},
"switch_to_order_menu": 0,
"cuisines": "Ice Cream",
"average_cost_for_two": 7,
"price_range": 1,
"currency": "$",
"offers": [],
"thumb": "",
"user_rating": {
"aggregate_rating": "2.9",
"rating_text": "Average",
"rating_color": "FFBA00",
"votes": "5"
},
"photos_url": "https://www.zomato.com/bass-vic/bassine-specialty-cheese-bass/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/bass-vic/bassine-specialty-cheese-bass/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/16607974",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/bass-vic/bassine-specialty-cheese-bass/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
{
"restaurant": {
"R": {
"res_id": 17649424
},
"apikey": "3d93604b4a84d85f374f39ea3b644132",
"id": "17649424",
"name": "Schobels' Restaurant",
"url": "https://www.zomato.com/columbus-tx/schobels-restaurant-columbus?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "2020 Milam St 78934",
"locality": "Columbus",
"city": "Columbus",
"city_id": 9241,
"latitude": "29.6965000000",
"longitude": "-96.5405000000",
"zipcode": "78934",
"country_id": 216,
"locality_verbose": "Columbus, Columbus"
},
"switch_to_order_menu": 0,
"cuisines": "German, Southern",
"average_cost_for_two": 25,
"price_range": 2,
"currency": "$",
"offers": [],
"thumb": "",
"user_rating": {
"aggregate_rating": "4.0",
"rating_text": "Very Good",
"rating_color": "5BA829",
"votes": "164"
},
"photos_url": "https://www.zomato.com/columbus-tx/schobels-restaurant-columbus/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/columbus-tx/schobels-restaurant-columbus/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/17649424",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/columbus-tx/schobels-restaurant-columbus/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
}
]
}
Error which I am getting:
org.json.JSONException: No value for name
Your jsonQuery contain JsonObject inside JsonObject named restaurant so you need to get JsonObject from JSONObject restaurant = restaurants.getJSONObject(i);
Like JSONObject restaurantsJSONObject =restaurant.getJSONObject("restaurant");
Try below example to get name from object
try {
JSONObject jsonObject = new JSONObject(jsonQuery);
if (jsonObject != null){
JSONArray restaurants = jsonObject.getJSONArray("restaurants");
for (int i = 0; i < restaurants.length(); i++){
JSONObject restaurant = restaurants.getJSONObject(i);
JSONObject restaurantsJSONObject =restaurant.getJSONObject("restaurant");
if(restaurantsJSONObject.has("name")) {
String tempName = restaurantsJSONObject.getString("name");
Log.d(TAG, "Restaurant name: " + tempName);
}
}
}
} catch (JSONException e) {
Log.d(TAG, "Exception catched: " + e);
e.printStackTrace();
}
Related
This is my JSON data i want to parse but am still new in deserialization, i want to get the following Attributes from this JSON data :
1.AirportCode.
2.Latutude.
3.Longitude.
This is the JSON containing two lists of the Airports.
{
"AirportResource": {
"Airports": {
"Airport": [{
"AirportCode": "AAL",
"Position": {
"Coordinate": {
"Latitude": 57.09305556,
"Longitude": 9.85
}
},
"CityCode": "AAL",
"CountryCode": "DK",
"LocationType": "Airport",
"Names": {
"Name": [{
"#LanguageCode": "xx",
"$": "Aalborg"
}, {
"#LanguageCode": "de",
"$": "Aalborg"
}, {
"#LanguageCode": "ru",
"$": "Ольборг"
}, {
"#LanguageCode": "pt",
"$": "Aalborg"
}, {
"#LanguageCode": "jp",
"$": "オールボア"
}, {
"#LanguageCode": "kr",
"$": "올보르그"
}, {
"#LanguageCode": "en",
"$": "Aalborg"
}, {
"#LanguageCode": "it",
"$": "Aalborg"
}, {
"#LanguageCode": "fr",
"$": "Aalborg"
}, {
"#LanguageCode": "es",
"$": "Aalborg"
}, {
"#LanguageCode": "ka",
"$": "奧爾堡"
}, {
"#LanguageCode": "pl",
"$": "Aalbork"
}, {
"#LanguageCode": "mi",
"$": "奥尔堡"
}]
},
"UtcOffset": 2,
"TimeZoneId": "Europe\/Copenhagen"
}, {
"AirportCode": "AAR",
"Position": {
"Coordinate": {
"Latitude": 56.30388889,
"Longitude": 10.62
}
},
"CityCode": "AAR",
"CountryCode": "DK",
"LocationType": "Airport",
"Names": {
"Name": [{
"#LanguageCode": "xx",
"$": "Aarhus"
}, {
"#LanguageCode": "en",
"$": "Aarhus"
}, {
"#LanguageCode": "de",
"$": "Aarhus"
}, {
"#LanguageCode": "it",
"$": "Aarhus"
}, {
"#LanguageCode": "fr",
"$": "Aarhus"
}, {
"#LanguageCode": "es",
"$": "Aarhus"
}]
},
"UtcOffset": 2,
"TimeZoneId": "Europe\/Copenhagen"
}]
},
"Meta": {
"#Version": "1.0.0",
"Link": [{
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/airports\/?limit=2&LHoperated=0&offset=0",
"#Rel": "self"
}, {
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/airports\/?limit=2&LHoperated=0&offset=2",
"#Rel": "next"
}, {
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/airports\/?limit=2&LHoperated=0&offset=1260",
"#Rel": "last"
}, {
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/cities\/{cityCode}",
"#Rel": "related"
}, {
"#Href": "https:\/\/api.lufthansa.com\/v1\/references\/countries\/{countryCode}",
"#Rel": "related"
}],
"TotalCount": 1261
}
}
}
Then my Java code:
EDITTED:
private void parseJson(String result)
{
try {
if (result!=null) {
JSONObject obj = new JSONObject(result).getJSONObject("AirportResource").getJSONObject("Airports");
JSONArray arr = obj.getJSONArray("Airport");
for (int i = 0; i < arr.length(); i++)
{
String AirportCode = arr.getJSONObject(i).getString("AAL");
String Latitude = arr.getJSONObject(i).getJSONObject("Position").getJSONObject("Coordinate").getString("Latitude");
String Longitude = arr.getJSONObject(i).getJSONObject("Position").getJSONObject("Coordinate").getString("Longitude");
System.out.println("Airport : " + AirportCode + " Latitude: " + Latitude+
" Longitude : " + Longitude );
}
}
else{
Toast.makeText(MainActivity.this,Config.POOR_NETWORK_CONNECTION, Toast.LENGTH_LONG).show();
}
}
catch (JSONException r){
System.out.println("ERROR PROB : "+ r);
}
}
The exception am getting is :
org.json.JSONException: No value for AirportResource
How can i parse this JSON kind of Data?
This will HOPEFULLY get you started.
private static void parseJson(JSONObject object) throws JSONException {
if (object!=null) {
JSONObject airportResource = object.getJSONObject("AirportResource");
JSONObject airports = airportResource.getJSONObject("Airports");
JSONArray airportArray = airports.getJSONArray("Airport");
for (int i = 0 ; i < airportArray.length(); i++) {
JSONObject airport = (JSONObject) airportArray.get(i);
//System.out.println(airport);
System.out.println("CityCode: " + airport.getString("CityCode"));
}
}
else{
//null
}
}
The output will be:
CityCode: AAL
CityCode: AAR
You didnt take the object of Airports. Inside Airports object is the Airport array and you are directly accessing it. Hence throwing error.
JSONObject obj2 = obj.getJSONObject("Airports");
Now get Json Array from obj
JsonArray jsonarray= obj2.getJsonArray("Airport");
Use the for loop on jsonarray's length now.
I recommend using this tool to view and formate your JSON properly.
this is the result
from here you could easily resolve your problem
JSONObject AirportResource= obj.getJSONObject("AirportResource");
JsonArray AirPorts= AirportResource.getJSONObject("Airports");
JsonArray jsonarray= AirPorts.getJsonArray("Airport");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj= AirportResource.get(i); do sth with it
obj.getString("key"); //do sth with it
}
response:
[
{
"id": "e9299032e8a34d168def176af7d62da3",
"createdAt": "Nov 8, 2017 9:46:40 AM",
"model": {
"id": "eeed0b6733a644cea07cf4c60f87ebb7",
"name": "color",
"app_id": "main",
"created_at": "May 11, 2016 11:35:45 PM",
"model_version": {}
},
"input": {
"id": "df6eae07cd86483f811c5a2202e782eb",
"data": {
"concepts": [],
"metadata": {},
"image": {
"url": "http://www.sachinmittal.com/wp-content/uploads/2017/04/47559184-image.jpg"
}
}
},
"data": [
{
"hex": "#f59b2d",
"webSafeHex": "#ffa500",
"webSafeColorName": "Orange",
"value": 0.0605
},
{
"hex": "#3f1303",
"webSafeHex": "#000000",
"webSafeColorName": "Black",
"value": 0.2085
},
{
"hex": "#a33303",
"webSafeHex": "#8b0000",
"webSafeColorName": "DarkRed",
"value": 0.3815
},
{
"hex": "#000000",
"webSafeHex": "#000000",
"webSafeColorName": "Black",
"value": 0.34275
},
{
"hex": "#f7ce93",
"webSafeHex": "#ffdead",
"webSafeColorName": "NavajoWhite",
"value": 0.00675
}
],
"status": {}
}
]
need to parse this reponse in json. Please help me out.
You can try something like this..
try{
JSONArray array= new JSONArray(Yourresponse);
for(int i=0; i<=array.length();i++){
JSONObject jsonObject=array.getJSONObject(i);
String id= jsonObject.getString("id");
String created_at= jsonObject.getString("createdAt");
String model_id = jsonObject.getJSONObject("model").getString("id");
String app_id=jsonObject.getJSONObject("model").getString("app_id");
//So On... Depends on your requirements. It's just an idea!
}
}
catch (Exception e){
e.printStackTrace();
}
My program parse JSON from file where is saved unstructured content of this json adress.
Unstructured json format from file json.txt:
{"total":3307,"watershed":100,"maxPage":5,"search":"http://10.103.80.149:3312/bin/sp?app=pinglun&outfmt=json&seek_timeout=400&gmt_create=1465228800~&validfeedback=1&item_id=538236063692&rate=1&layer_quota=500000&status=0,-1&order=algo_sort:des&s=0&n=20&is_wireless=0&user_id=0&utd_id=ba3290d86b9fdcd927e8ae83fde1ee64&is_click_sku=0","currentPageNum":1,"comments":[{"auction":{"title":"","thumbnail":""....
For better view in structured form:
{
"total": 3307,
"watershed": 100,
"maxPage": 5,
"search": "http://10.103.80.162:3312/bin/sp?app=pinglun&outfmt=json&seek_timeout=400&gmt_create=1465228800~&validfeedback=1&item_id=538236063692&rate=1&layer_quota=500000&status=0,-1&order=algo_sort:des&s=0&n=20&is_wireless=0&user_id=0&is_click_sku=0",
"currentPageNum": 1,
"comments": [
{
"auction": {
"title": "",
"thumbnail": "",
"aucNumId": "538236063692",
"link": "//item.taobao.com/item.htm?id=538236063692",
"auctionPic": "//img.alicdn.com/bao/uploaded/null_40x40.jpg",
"sku": "机身颜色:黑色(顶级配置)[移动+联通]  套餐类型:官方标配  存储容量:64MB  版本类型:中国大陆"
},
"promotionType": "活动促销 ",
"enableSNS": false,
"tag": "",
"appendCanExplainable": false,
"showCuIcon": true,
"validscore": 1,
"award": "",
"noQna": true,
"appendList": [
{
"photos": [
],
"content": "老人机使用效果好,功能强大,非常值得拥有!!!",
"vicious": "",
"reply": null,
"show": true,
"dayAfterConfirm": 0,
"appendId": 290673146633
}
],
"from": "",
"date": "2016年11月05日 16:46",
"dayAfterConfirm": 0,
"bidPriceMoney": {
"cent": 7905,
"amount": 79.05,
"currencyCode": "CNY",
"centFactor": 100,
"displayUnit": "元",
"currency": {
"defaultFractionDigits": 2,
"currencyCode": "CNY",
"symbol": "¥"
}
},
"rate": "1",
"o2oRate": null,
"propertiesAvg": "0.0",
"showDepositIcon": false,
"rateId": 290589793921,
"creditFraudRule": 0,
"useful": 0,
"reply": null,
"append": {
"photos": [
],
"content": "老人机使用效果好,功能强大,非常值得拥有!!!",
"vicious": "",
.
.
.
.}
And I need to parse only chinese comments in element "content" e.g. "老人机使用效果好,功能强大,非常值得拥有!!!", but I don't know how to works with this element in JSONArray with json-simple.
Here is example of code:
public class Final {
public static void main(String[] args) throws IOException, JSONException {
String jsonData = "";
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("json.txt"));
while ((line = br.readLine()) != null) {
jsonData += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("\nFile Content: \n" + jsonData1); // displays all content
JSONObject obj = new JSONObject(jsonData);
System.out.println("search: " + obj.getString("search"));
System.out.println("comments: " + obj.getJSONObject("comments"));
}
}
Could you please help me with this problem?
I've got the title, author, and published date from json data to my android app.
I'm trying to get event_start_date and event_location, but failed. can anyone help me how I can get it?
Json:
{
"status": "ok",
"count": 1,
"count_total": 29,
"pages": 29,
"posts": [
{
"id": 2815,
"type": "event",
"slug": "itb-integrated-career-days",
"url": "http://example.com/event/itb-integrated-career-days/",
"status": "publish",
"title": "Title",
"title_plain": "Title",
"content": "<p>test</p>\n",
"excerpt": "<p>test […]</p>\n",
"date": "2015-09-25 01:09:40",
"modified": "2015-09-29 22:52:35",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "john",
"name": "john",
"first_name": "",
"last_name": "",
"nickname": "john",
"url": "",
"description": ""
},
"comments": [],
"attachments": [
{
"id": 2817,
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015.gif",
"slug": "bannertkt102015",
"title": "bannertkt102015",
"description": "",
"caption": "",
"parent": 2815,
"mime_type": "image/gif",
"images": {
"full": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015.gif",
"width": 1000,
"height": 563
},
"thumbnail": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015-150x150.gif",
"width": 150,
"height": 150
},
"medium": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015-300x169.gif",
"width": 300,
"height": 169
},
"large": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015.gif",
"width": 1000,
"height": 563
},
"blog-default": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015-806x300.gif",
"width": 806,
"height": 300
}
}
},
{
"id": 2818,
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008.jpg",
"slug": "2015-09-25_012008",
"title": "2015-09-25_012008",
"description": "",
"caption": "",
"parent": 2815,
"mime_type": "image/jpeg",
"images": {
"full": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008.jpg",
"width": 589,
"height": 529
},
"thumbnail": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008-300x269.jpg",
"width": 300,
"height": 269
},
"large": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008.jpg",
"width": 589,
"height": 529
},
"blog-default": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008-589x300.jpg",
"width": 589,
"height": 300
}
}
}
],
"comment_count": 0,
"comment_status": "open",
"thumbnail": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008-150x150.jpg",
"custom_fields": {
"event_location": [
"New York"
],
"event_start_date": [
"10/23/2015"
],
"event_start_time": [
"09:00 AM"
],
"event_start_date_number": [
"1445590800"
],
"event_address_country": [
"US"
],
"event_address_state": [
"Jawdst"
],
"event_address_city": [
"New York"
],
"event_address_address": [
"Gedung Sasana Budaya Ganesha (Sabuga) Jalan Tamansari 73, New York"
],
"event_address_zip": [
"42132"
],
"event_phone": [
"5345"
],
"post_views_count": [
"23"
]
}
}
]
}
And my function
public void parseJson(JSONObject json) {
try {
info.pages = json.getInt("pages");
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
info.feedList = new ArrayList<PostItem>();
for (int i = 0; i < posts.length(); i++) {
Log.v("INFO",
"Step 3: item " + (i + 1) + " of " + posts.length());
try {
JSONObject post = (JSONObject) posts.getJSONObject(i);
PostItem item = new PostItem();
item.setTitle(Html.fromHtml(post.getString("title"))
.toString());
item.setDate(post.getString("date"));
item.setId(post.getInt("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("content"));
if (post.has("author")) {
Object author = post.get("author");
if (author instanceof JSONArray
&& ((JSONArray) author).length() > 0) {
author = ((JSONArray) author).getJSONObject(0);
}
if (author instanceof JSONObject
&& ((JSONObject) author).has("name")) {
item.setAuthor(((JSONObject) author)
.getString("name"));
}
}
if (post.has("tags") && post.getJSONArray("tags").length() > 0) {
item.setTag(((JSONObject) post.getJSONArray("tags").get(0)).getString("slug"));
}
// TODO do we dear to remove catch clause?
try {
boolean thumbnailfound = false;
if (post.has("thumbnail")) {
String thumbnail = post.getString("thumbnail");
if (thumbnail != "") {
item.setThumbnailUrl(thumbnail);
thumbnailfound = true;
}
}
if (post.has("attachments")) {
JSONArray attachments = post
.getJSONArray("attachments");
// checking how many attachments post has and
// grabbing the first one
if (attachments.length() > 0) {
JSONObject attachment = attachments
.getJSONObject(0);
item.setAttachmentUrl(attachment
.getString("url"));
// if we do not have a thumbnail yet, get
// one now
if (attachment.has("images")
&& !thumbnailfound) {
JSONObject thumbnail;
if (attachment.getJSONObject("images")
.has("post-thumbnail")) {
thumbnail = attachment
.getJSONObject("images")
.getJSONObject(
"post-thumbnail");
item.setThumbnailUrl(thumbnail
.getString("url"));
} else if (attachment.getJSONObject(
"images").has("thumbnail")) {
thumbnail = attachment
.getJSONObject("images")
.getJSONObject("thumbnail");
item.setThumbnailUrl(thumbnail
.getString("url"));
}
}
}
}
} catch (Exception e) {
Log.v("INFO",
"Item "
+ i
+ " of "
+ posts.length()
+ " will have no thumbnail or image because of exception!");
e.printStackTrace();
}
if (item.getId() != info.ignoreId)
info.feedList.add(item);
} catch (Exception e) {
Log.v("INFO", "Item " + i + " of " + posts.length()
+ " has been skipped due to exception!");
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This should do it
JSONObject custom_fields = post.getJSONObject("custom_fields");
JSONArray event_start_date_array = custom_fields.getJSONArray("event_start_date");
JSONArray event_location_array = custom_fields.getJSONArray("event_location");
String event_start_date = event_start_date_array.getString(0);
String event_location = event_location_array.getString(0);
I am going to get facebook read_books
The file is in this format:
{
"data": [
{
"id": "270170479804513",
"from": {
"name": "L I",
"id": "1000022"
},
"start_time": "2014-01-22T09:31:00+0000",
"publish_time": "2014-01-22T09:31:00+0000",
"application": {
"name": "Books",
"id": "174275722710475"
},
"data": {
"book": {
"id": "133556360140246",
"url": "https://www.facebook.com/pages/Pride-and-Prejudice/133556360140246",
"type": "books.book",
"title": "Pride and Prejudice"
}
},
"type": "books.reads",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
},
{
"id": "270170328",
"from": {
"name": "h",
"id": "100004346894022"
},
"start_time": "2014-01-22T09:29:42+0000",
"publish_time": "2014-01-22T09:29:42+0000",
"application": {
"name": "Books",
"id": "174275722710475"
},
"data": {
"book": {
"id": "104081659627680",
"url": "https://www.facebook.com/pages/Gulistan-of-Sadi/104081659627680",
"type": "books.book",
"title": "Gulistan of Sa'di"
}
},
"type": "books.reads",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
}
],
I need books titles and their URL. I run the below code but I get Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String
while ((inputLine = in.readLine()) != null)
{
s = s + inputLine + "\r\n";
if (s == null) {
break;
}
t = t + inputLine + "\r\n";
}
in.close();
t = t.substring(0, t.length() - 2);
System.out.println(t);
Object dataObj =JSONValue.parse(t);
System.out.println(dataObj);
JSONObject dataJson = (JSONObject) dataObj;
JSONArray data = (JSONArray) dataJson.get("data");
for (Object o: data)
{
JSONObject indata= (JSONObject) o;
Object indatafirst=(JSONObjec`enter code here`t).get("0");
String inndata=(String) indatafirst.get("data");
System.out.println("inndata"+inndata);
}}
but it is not true
The problem is with the following line:
String inndata=(String) indatafirst.get("data");
The data field in the JSON is not a String, it's a nested JSON object.
"data": {
"book": {
"id": "104081659627680",
"url": "https://www.facebook.com/pages/Gulistan-of-Sadi/104081659627680",
"type": "books.book",
"title": "Gulistan of Sa'di"
}
}
This explains your ClassCastException.
Instead you should do something like:
JSONObject data = (JSONObject) indatafirst.get("data");
JSONObject book = (JSONObject) data.get("book");
String bookTitle = book.get("title");