JSON content from file via Java - java

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": "机身颜色:黑色(顶级配置)[移动+联通] &nbsp套餐类型:官方标配 &nbsp存储容量:64MB &nbsp版本类型:中国大陆"
},
"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?

Related

How can I get inside info object using volley in android java

this is the json data and i want to display the info object using volley in android java i hope you can answer this question thank you
"data": {
"type": "customer",
"name": "Sasmple name",
"phone": "1234567",
"email": "sample#gmail.com",
"email_verified_at": null,
"created_at": "2021-05-04T08:24:49.000000Z",
"updated_at": "2021-05-04T08:24:49.000000Z",
"info": {
"id": 63,
"user_id": 381,
"fname": "Sample",
"mname": null,
"lname": "Name",
"gender": null,
"image": null,
"birthdate": null,
"address": "Sample, Sample City (capital), Sample",
"address_code": "{\"region\":\"07\",\"province\":\"0722\",\"citymun\":\"072217\",\"barangay\":\"072217027\"}",
"bank_number": "17171717171717171717",
"bank_name": "Sample bank",
"created_at": "2021-05-04T08:24:49.000000Z",
"updated_at": "2021-05-04T08:24:49.000000Z"
}
}
and this is my code that i used
JSONObject json= null;
try {
json = new JSONObject("info");
for(int i=0; i<json.length(); i++){
JSONObject item = json.getJSONObject(String.valueOf(json));
String province_id = item.getString("id");
String province_code = item.getString("fname");
String province_desc = item.getString("lname");
String province_regcode = item.getString("address");
String province_citycode = item.getString("address_code");
}
} catch (JSONException e) {
e.printStackTrace();
}
Please read more about JSON Object and Json Array here
To answer for your question
try {
JSONObject jsonData = new JSONObject(httpStringResponse);
JSONObject infoItem = json.getJSONObject("info");
String province_id = infoItem.getString("id");
String province_code = infoItem.getString("fname");
String province_desc = infoItem.getString("lname");
String province_regcode = infoItem.getString("address");
String province_citycode = infoItem.getString("address_code");
} catch (JSONException e) {
e.printStackTrace();
}

Unable to extract out name in 4 level deep nested JSON array

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

Nested JSON Array in Java

I need to create a json response like the one below. I tried with some code but couldn't able to get what i need. Need help in java code to create nested array to group the food items according to the categories along with the category details like in below json
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}
}
What i tried so far will give response in one single array.
#Path("/items")
public class HotelsMenu {
#GET
#Path("/getitems")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("hotelcode") String hotelcode) {
JSONObject response = new JSONObject();
JSONArray hotelDetails = checkCredentials(hotelcode);
try {
response.put("hotels", hotelDetails);
response.put("status", (hotelDetails == new JSONArray()) ? "false" : "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response.toString();
}
private JSONArray checkCredentials(String hotelcode) {
System.out.println("Inside checkCredentials");
JSONArray result = new JSONArray();
try {
result = DBConnection.checkItems(hotelcode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static JSONArray checkItems(String hotelcode) throws Exception {
int id;
String code = hotelcode + "_mnu";
String name = null;
String name1 = null;
String status;
String price;
Connection dbConn = null;
Connection dbConn1 = null;
JSONArray hotels = new JSONArray();
JSONArray menu = new JSONArray();
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "SELECT * FROM " + code + " where Status='1'";
System.out.println(query);
ResultSet rs1 = stmt.executeQuery(query);
System.out.println("hai");
while (rs1.next()) {
JSONObject hotel = new JSONObject();
id = rs1.getInt("Id");
hotel.put("id", id);
code = rs1.getString("Code");
System.out.println(code);
hotel.put("code", code);
name = rs1.getString("Name");
hotel.put("name", name);
status = rs1.getString("Status");
hotel.put("status", status);
hotels.put(hotel);
System.out.println("Hotel1:" + hotels);
try {
dbConn1 = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt1 = dbConn1.createStatement();
String query1 = "SELECT * FROM " + code + " where Status='1' ";
System.out.println(query1);
ResultSet rs2 = stmt1.executeQuery(query1);
while (rs2.next()) {
JSONArray hotel1 = new JSONArray();
JSONObject hotelmenu = new JSONObject();
id = rs2.getInt("Id");
hotelmenu.put("id", id);
name1 = rs2.getString("Name");
hotelmenu.put("name", name1);
price = rs2.getString("Price");
hotelmenu.put("price", price);
hotel1.put(hotelmenu);
hotels.put(hotel1);
System.out.println(hotels);
}
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return hotels;
}
}
As previous answers suggests, you should re-design your model. I just did a quick restructuring of it. Check if this serves your purpose -
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}}
If the structure is OK, let know if you want help with the Java code to generate the above Json.
Also maybe go through the following libraries -
Jackson tutorial and Gson tutorial
//import java.util.ArrayList;
//import org.bson.Document;
Document root = new Document();
Document rootMenu = new Document();
ArrayList rootMenuItems = new ArrayList();
Document rootMenuItems0 = new Document();
ArrayList rootMenuItems0Sub_items = new ArrayList();
Document rootMenuItems0Sub_items0 = new Document();
Document rootMenuItems0Sub_items1 = new Document();
Document rootMenuItems1 = new Document();
ArrayList rootMenuItems1Sub_items = new ArrayList();
Document rootMenuItems1Sub_items0 = new Document();
Document rootMenuItems2 = new Document();
ArrayList rootMenuItems2Sub_items = new ArrayList();
Document rootMenuItems2Sub_items0 = new Document();
Document rootMenuItems2Sub_items1 = new Document();
rootMenuItems0.append("id", 1);
rootMenuItems0.append("code", "hot1_sub1_mnu");
rootMenuItems0.append("name", "Mutton");
rootMenuItems0.append("status", "1");
rootMenuItems0Sub_items0.append("id", "01");
rootMenuItems0Sub_items0.append("name", "Mutton Pepper Fry");
rootMenuItems0Sub_items0.append("price", "100");
rootMenuItems0Sub_items1.append("id", "02");
rootMenuItems0Sub_items1.append("name", "Mutton Curry");
rootMenuItems0Sub_items1.append("price", "100");
rootMenuItems1.append("id", "2");
rootMenuItems1.append("code", "hot1_sub2_mnu");
rootMenuItems1.append("name", "Sea Food");
rootMenuItems1.append("status", "1");
rootMenuItems1Sub_items0.append("id", "01");
rootMenuItems1Sub_items0.append("name", "Fish Fry");
rootMenuItems1Sub_items0.append("price", "150");
rootMenuItems2.append("id", "3");
rootMenuItems2.append("code", "hot1_sub3_mnu");
rootMenuItems2.append("name", "Noodles");
rootMenuItems2.append("status", "1");
rootMenuItems2Sub_items0.append("id", "01");
rootMenuItems2Sub_items0.append("name", "Chicken Noodles");
rootMenuItems2Sub_items0.append("price", "70");
rootMenuItems2Sub_items1.append("id", "02");
rootMenuItems2Sub_items1.append("name", "Egg Noodles");
rootMenuItems2Sub_items1.append("price", "60");
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0Sub_items0.isEmpty()) {
rootMenuItems0Sub_items.add(rootMenuItems0Sub_items0);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0Sub_items1.isEmpty()) {
rootMenuItems0Sub_items.add(rootMenuItems0Sub_items1);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0.isEmpty()) {
rootMenuItems.add(rootMenuItems0);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems1Sub_items.isEmpty()) {
rootMenuItems1.append("sub_items", rootMenuItems1Sub_items);
}
if (!rootMenuItems1Sub_items0.isEmpty()) {
rootMenuItems1Sub_items.add(rootMenuItems1Sub_items0);
}
if (!rootMenuItems1Sub_items.isEmpty()) {
rootMenuItems1.append("sub_items", rootMenuItems1Sub_items);
}
if (!rootMenuItems1.isEmpty()) {
rootMenuItems.add(rootMenuItems1);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2Sub_items0.isEmpty()) {
rootMenuItems2Sub_items.add(rootMenuItems2Sub_items0);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2Sub_items1.isEmpty()) {
rootMenuItems2Sub_items.add(rootMenuItems2Sub_items1);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2.isEmpty()) {
rootMenuItems.add(rootMenuItems2);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenu.isEmpty()) {
root.append("menu", rootMenu);
}
System.out.println(root.toJson());

How get array value from nested json data (java android)

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

How to read a JSON file in Java using org.json.simple package

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

Categories

Resources