I am trying to decode the json objects into multiple strings.I dont know how to parse the json object.
here is my json string
{"page_1":"{\"city\":\"Bangalore\",\"locality\":\"Battarahalli\",\"Name_of_Person\":\"xxx\",\"User_email_address\":\"xxx#gmail.com\",\"user_phone_number\":\"\",\"sub_locality\":\"\",\"street_name\":\"7th Cross Road, Near Reliance Fresh, T.c Palya,\",\"home_plot_no\":\"45\",\"pin_code\":\"560049\",\"project_society_build_name\":\"Sunshine Layout\",\"landmark_reference_1\":\"\",\"landmark_reference_2\":\"\",\"No_of_Schools\":20,\"No_of_Hospitals\":20,\"No_of_Metro\":0,\"No_of_Mall\":11,\"No_of_Park\":10,\"Distance_of_schools\":1.55,\"Distance_of_Hospitals\":2.29,\"Distance_of_Metro\":0,\"Distance_of_Mall\":1.55,\"Distance_of_Park\":2.01,\"lat\":13.0243273,\"lng\":77.7077906,\"ipinfo\":{\"ip\":\"113.193.30.130\",\"hostname\":\"No Hostname\",\"city\":\"\",\"region\":\"\",\"country\":\"IN\",\"loc\":\"20.0000,77.0000\",\"org\":\"AS45528 Tikona Digital Networks Pvt Ltd.\"}}","page_2":"{\"home_type\":\"Flat\",\"area\":\"1350\",\"beds\":\"3 BHK\",\"bath_rooms\":2,\"building_age\":\"1\",\"floors\":2,\"balcony\":2,\"amenities\":\"premium\",\"amenities_options\":{\"gated_security\":\"\",\"physical_security\":\"\",\"cctv_camera\":\"\",\"controll_access\":\"\",\"elevator\":true,\"power_back_up\":\"\",\"parking\":true,\"partial_parking\":\"\",\"onsite_maintenance_store\":\"\",\"open_garden\":\"\",\"party_lawn\":\"\",\"amenities_balcony\":\"\",\"club_house\":\"\",\"fitness_center\":\"\",\"swimming_pool\":\"\",\"party_hall\":\"\",\"tennis_court\":\"\",\"basket_ball_court\":\"\",\"squash_coutry\":\"\",\"amphi_theatre\":\"\",\"business_center\":\"\",\"jogging_track\":\"\",\"convinience_store\":\"\",\"guest_rooms\":\"\"},\"interior\":\"regular\",\"interior_options\":{\"tiles\":true,\"marble\":\"\",\"wooden\":\"\",\"modular_kitchen\":\"\",\"partial_modular_kitchen\":\"\",\"gas_pipe\":\"\",\"intercom_system\":\"\",\"air_conditioning\":\"\",\"partial_air_conditioning\":\"\",\"wardrobe\":\"\",\"sanitation_fixtures\":\"\",\"false_ceiling\":\"\",\"partial_false_ceiling\":\"\",\"recessed_lighting\":\"\"},\"location\":\"regular\",\"location_options\":{\"good_view\":true,\"transporation_hub\":true,\"shopping_center\":\"\",\"hospital\":\"\",\"school\":\"\",\"ample_parking\":\"\",\"park\":\"\",\"temple\":\"\",\"bank\":\"\",\"less_congestion\":\"\",\"less_pollution\":\"\"},\"maintenance\":\"\",\"maintenance_value\":\"\",\"near_by\":{\"school\":\"\",\"hospital\":\"\",\"mall\":\"\",\"park\":\"\",\"metro\":\"\",\"Near_by_school\":\"Little Champ Gurukulam Pre School \\\/ 1.52 km\",\"Near_by_hospital\":\"Suresh Hospital \\\/ 2.16 km\",\"Near_by_mall\":\"LORVEN LEO \\\/ 2.13 km\",\"Near_by_park\":\"SURYA ENCLAIVE \\\/ 2.09 km\"},\"city\":\"Bangalore\",\"locality\":\"Battarahalli\",\"token\":\"344bd4f0fab99b460873cfff6befb12f\"}"}
I tried like this
String JSON = "{\"page_1\":{\"city\":\"Bangalore\",\"locality\":\"Anekal\",\"Name_of_Person\":\"sas\",\"User_email_address\":\"ddd32#gmail.com\",\"user_phone_number\":\"\",\"sub_locality\":\"\",\"street_name\":\"farahana\",\"home_plot_no\":\"50\",\"pin_code\":\"\",\"project_society_build_name\":\"\",\"landmark_reference_1\":\"\",\"landmark_reference_2\":\"\",\"No_of_Schools\":20,\"No_of_Hospitals\":8,\"No_of_Metro\":1,\"No_of_Mall\":1,\"No_of_Park\":0,\"Distance_of_schools\":2.51,\"Distance_of_Hospitals\":0.43,\"Distance_of_Metro\":2.55,\"Distance_of_Mall\":0.89,\"Distance_of_Park\":0,\"lat\":12.7105259,\"lng\":77.6911295,\"ipinfo\":{\"ip\":\"113.193.30.130\",\"hostname\":\"No Hostname\",\"city\":\"\",\"region\":\"\",\"country\":\"IN\",\"loc\":\"20.0000,77.0000\",\"org\":\"AS45528 Tikona Digital Networks Pvt Ltd.\"}}\n
JSONObject obj = new JSONObject(JSON);
String city = (String) obj.get("city");
System.out.println(city);
But it throws error only
Expected a ',' or '}' at 711 [character 1 line 2]
any help will be appreciated.
Can't fit this in comment, but will try to be short:
First thing is that you get Expected a ',' or '}' at 711 [character 1 line 2] because you just copied first half of your initial json. Your initial Json looks like this: {"page_1": "...", "page_2": "..."}, but json in your code looks like {"page_1": {...} and you are missing closing }.
If you really need json from your code you have to
1) add closing } to the end of String JSON
2) Take page_1 object first and then take city string from it. Here is demo:
String JSON = "{\"page_1\":{\"city\":\"Bangalore\",\"locality\":\"Anekal\",\"Name_of_Person\":\"sas\",\"User_email_address\":\"ddd32#gmail.com\",\"user_phone_number\":\"\",\"sub_locality\":\"\",\"street_name\":\"farahana\",\"home_plot_no\":\"50\",\"pin_code\":\"\",\"project_society_build_name\":\"\",\"landmark_reference_1\":\"\",\"landmark_reference_2\":\"\",\"No_of_Schools\":20,\"No_of_Hospitals\":8,\"No_of_Metro\":1,\"No_of_Mall\":1,\"No_of_Park\":0,\"Distance_of_schools\":2.51,\"Distance_of_Hospitals\":0.43,\"Distance_of_Metro\":2.55,\"Distance_of_Mall\":0.89,\"Distance_of_Park\":0,\"lat\":12.7105259,\"lng\":77.6911295,\"ipinfo\":{\"ip\":\"113.193.30.130\",\"hostname\":\"No Hostname\",\"city\":\"\",\"region\":\"\",\"country\":\"IN\",\"loc\":\"20.0000,77.0000\",\"org\":\"AS45528 Tikona Digital Networks Pvt Ltd.\"}}}";
try {
JSONObject obj = new JSONObject(JSON);
JSONObject page_1 = obj.getJSONObject("page_1");
String city = page_1.getString("city");
System.out.println(city);
} catch (JSONException e) {
e.printStackTrace();
}
But Json in your 1-st string is not the same as in your code. Your initial Json has this format: {"page_1": "...", "page_2": "..."} and as you can see, there are strings and not objects for values. So it is a little bit different and here is demo:
String JSON = "{\"page_1\":\"{\\\"city\\\":\\\"Bangalore\\\",\\\"locality\\\":\\\"Battarahalli\\\",\\\"Name_of_Person\\\":\\\"xxx\\\",\\\"User_email_address\\\":\\\"xxx#gmail.com\\\",\\\"user_phone_number\\\":\\\"\\\",\\\"sub_locality\\\":\\\"\\\",\\\"street_name\\\":\\\"7th Cross Road, Near Reliance Fresh, T.c Palya,\\\",\\\"home_plot_no\\\":\\\"45\\\",\\\"pin_code\\\":\\\"560049\\\",\\\"project_society_build_name\\\":\\\"Sunshine Layout\\\",\\\"landmark_reference_1\\\":\\\"\\\",\\\"landmark_reference_2\\\":\\\"\\\",\\\"No_of_Schools\\\":20,\\\"No_of_Hospitals\\\":20,\\\"No_of_Metro\\\":0,\\\"No_of_Mall\\\":11,\\\"No_of_Park\\\":10,\\\"Distance_of_schools\\\":1.55,\\\"Distance_of_Hospitals\\\":2.29,\\\"Distance_of_Metro\\\":0,\\\"Distance_of_Mall\\\":1.55,\\\"Distance_of_Park\\\":2.01,\\\"lat\\\":13.0243273,\\\"lng\\\":77.7077906,\\\"ipinfo\\\":{\\\"ip\\\":\\\"113.193.30.130\\\",\\\"hostname\\\":\\\"No Hostname\\\",\\\"city\\\":\\\"\\\",\\\"region\\\":\\\"\\\",\\\"country\\\":\\\"IN\\\",\\\"loc\\\":\\\"20.0000,77.0000\\\",\\\"org\\\":\\\"AS45528 Tikona Digital Networks Pvt Ltd.\\\"}}\",\"page_2\":\"{\\\"home_type\\\":\\\"Flat\\\",\\\"area\\\":\\\"1350\\\",\\\"beds\\\":\\\"3 BHK\\\",\\\"bath_rooms\\\":2,\\\"building_age\\\":\\\"1\\\",\\\"floors\\\":2,\\\"balcony\\\":2,\\\"amenities\\\":\\\"premium\\\",\\\"amenities_options\\\":{\\\"gated_security\\\":\\\"\\\",\\\"physical_security\\\":\\\"\\\",\\\"cctv_camera\\\":\\\"\\\",\\\"controll_access\\\":\\\"\\\",\\\"elevator\\\":true,\\\"power_back_up\\\":\\\"\\\",\\\"parking\\\":true,\\\"partial_parking\\\":\\\"\\\",\\\"onsite_maintenance_store\\\":\\\"\\\",\\\"open_garden\\\":\\\"\\\",\\\"party_lawn\\\":\\\"\\\",\\\"amenities_balcony\\\":\\\"\\\",\\\"club_house\\\":\\\"\\\",\\\"fitness_center\\\":\\\"\\\",\\\"swimming_pool\\\":\\\"\\\",\\\"party_hall\\\":\\\"\\\",\\\"tennis_court\\\":\\\"\\\",\\\"basket_ball_court\\\":\\\"\\\",\\\"squash_coutry\\\":\\\"\\\",\\\"amphi_theatre\\\":\\\"\\\",\\\"business_center\\\":\\\"\\\",\\\"jogging_track\\\":\\\"\\\",\\\"convinience_store\\\":\\\"\\\",\\\"guest_rooms\\\":\\\"\\\"},\\\"interior\\\":\\\"regular\\\",\\\"interior_options\\\":{\\\"tiles\\\":true,\\\"marble\\\":\\\"\\\",\\\"wooden\\\":\\\"\\\",\\\"modular_kitchen\\\":\\\"\\\",\\\"partial_modular_kitchen\\\":\\\"\\\",\\\"gas_pipe\\\":\\\"\\\",\\\"intercom_system\\\":\\\"\\\",\\\"air_conditioning\\\":\\\"\\\",\\\"partial_air_conditioning\\\":\\\"\\\",\\\"wardrobe\\\":\\\"\\\",\\\"sanitation_fixtures\\\":\\\"\\\",\\\"false_ceiling\\\":\\\"\\\",\\\"partial_false_ceiling\\\":\\\"\\\",\\\"recessed_lighting\\\":\\\"\\\"},\\\"location\\\":\\\"regular\\\",\\\"location_options\\\":{\\\"good_view\\\":true,\\\"transporation_hub\\\":true,\\\"shopping_center\\\":\\\"\\\",\\\"hospital\\\":\\\"\\\",\\\"school\\\":\\\"\\\",\\\"ample_parking\\\":\\\"\\\",\\\"park\\\":\\\"\\\",\\\"temple\\\":\\\"\\\",\\\"bank\\\":\\\"\\\",\\\"less_congestion\\\":\\\"\\\",\\\"less_pollution\\\":\\\"\\\"},\\\"maintenance\\\":\\\"\\\",\\\"maintenance_value\\\":\\\"\\\",\\\"near_by\\\":{\\\"school\\\":\\\"\\\",\\\"hospital\\\":\\\"\\\",\\\"mall\\\":\\\"\\\",\\\"park\\\":\\\"\\\",\\\"metro\\\":\\\"\\\",\\\"Near_by_school\\\":\\\"Little Champ Gurukulam Pre School \\\\\\/ 1.52 km\\\",\\\"Near_by_hospital\\\":\\\"Suresh Hospital \\\\\\/ 2.16 km\\\",\\\"Near_by_mall\\\":\\\"LORVEN LEO \\\\\\/ 2.13 km\\\",\\\"Near_by_park\\\":\\\"SURYA ENCLAIVE \\\\\\/ 2.09 km\\\"},\\\"city\\\":\\\"Bangalore\\\",\\\"locality\\\":\\\"Battarahalli\\\",\\\"token\\\":\\\"344bd4f0fab99b460873cfff6befb12f\\\"}\"}";
try {
JSONObject obj = new JSONObject(JSON);
String page_1Str = obj.getString("page_1");
JSONObject page_1 = new JSONObject(page_1Str);
String city = page_1.getString("city");
System.out.println(city);
} catch (JSONException e) {
e.printStackTrace();
}
you use this JSON. because you left a close curly braces:
{
"page_1": {
"city": "Bangalore",
"locality": "Anekal",
"Name_of_Person": "sas",
"User_email_address": "ddd32#gmail.com",
"user_phone_number": "",
"sub_locality": "",
"street_name": "farahana",
"home_plot_no": "50",
"pin_code": "",
"project_society_build_name": "",
"landmark_reference_1": "",
"landmark_reference_2": "",
"No_of_Schools": 20,
"No_of_Hospitals": 8,
"No_of_Metro": 1,
"No_of_Mall": 1,
"No_of_Park": 0,
"Distance_of_schools": 2.51,
"Distance_of_Hospitals": 0.43,
"Distance_of_Metro": 2.55,
"Distance_of_Mall": 0.89,
"Distance_of_Park": 0,
"lat": 12.7105259,
"lng": 77.6911295,
"ipinfo": {
"ip": "113.193.30.130",
"hostname": "No Hostname",
"city": "",
"region": "",
"country": "IN",
"loc": "20.0000,77.0000",
"org": "AS45528 Tikona Digital Networks Pvt Ltd."
}
}
}
you use json pro lint to debug your JSON: The link is
http://pro.jsonlint.com/
public class Kunfu {
public static void main(String a[]) throws JSONException{
String JSON = "{\"page_1\":{\"city\":\"Bangalore\",\"locality\":\"Anekal\",\"Name_of_Person\":\"sas\",\"User_email_address\":\"ddd32#gmail.com\",\"user_phone_number\":\"\",\"sub_locality\":\"\",\"street_name\":\"farahana\",\"home_plot_no\":\"50\",\"pin_code\":\"\",\"project_society_build_name\":\"\",\"landmark_reference_1\":\"\",\"landmark_reference_2\":\"\",\"No_of_Schools\":20,\"No_of_Hospitals\":8,\"No_of_Metro\":1,\"No_of_Mall\":1,\"No_of_Park\":0,\"Distance_of_schools\":2.51,\"Distance_of_Hospitals\":0.43,\"Distance_of_Metro\":2.55,\"Distance_of_Mall\":0.89,\"Distance_of_Park\":0,\"lat\":12.7105259,\"lng\":77.6911295,\"ipinfo\":{\"ip\":\"113.193.30.130\",\"hostname\":\"No Hostname\",\"city\":\"\",\"region\":\"\",\"country\":\"IN\",\"loc\":\"20.0000,77.0000\",\"org\":\"AS45528 Tikona Digital Networks Pvt Ltd.\"}}}\n";
JSONObject obj = new JSONObject(JSON);
String city = (String) obj.getJSONObject("page_1").get("city");
System.out.println(city);
}}
output:
Bangalore
This code is working well. you try it and you add JSON jar
The jar file link is:
http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm
Related
I am trying to read a json file and after traversing to attrib`s called "paymentKey" and "Session key" and changing their values through JSONObject , the post operation failing.
When i checked the out json after performing above changes it seems that structure is bit unordered , changed and even got to learn that json is not an valid one.
This is bit annoying and not sure how to keep the json format in tag after replacing the attrib`s values.
Below is the Json used
{
"idempotentId": "133215472229",
"customerId": "12345",
"brandId": "ANCHOR",
"sellingChannel": "WEBOA",
"items": [
{
"lineItemId": 123,
"productId": "ANCHOR-WEBOA-640213214",
"price": 1.19,
"quantity": 1,
"modifierGroups": [],
"childItems": [],
"note": " Drink without snacks"
}
],
"fulfillment": {
"email": "12#gmail.com",
"phoneNumber": "+912222621",
"fulfillmentType": "PickUp",
"asap": true,
"pickupFirstName": "Kiran",
"pickupLastName": "Kumar",
"locationId": "33211111"
},
"payment": {
"paymentKey": "12222-444-555-2222-44444121e",
"sessionKey": "02f3waAjHJnVCTstOIu0jcSZfm_1HnGum1lZdsu6iDlLxxjO1FYsG9DHz9130ZzMMkjYY9j5w.7V8CijbmiPSo5ESDsq5hsQ.RpYSS5wkgoSSOMjktEyDTHZh1IPq0wNayp--DE3HE53uUgTEehCvHjSsUP5q8U2ZN1kZXbsufwm_mRCV8hLCrmWVTchhVUTJtmEpyYy142DtSp1ikXOVzGN5i9z_oP5e79QvgmU7_n1C5DeARFRagQClT87vUFBUfleSbLaRyH5v3wkU7ji9URUetcq1iAfS5-cNt6-uJaulFJc2y6uNdn0OtjIe74Hp5G7Gx54VYggduoqx5X1rsCssobfUSJUDLt_vVpz5BvhQM88EaysMAB6EcQHoOnZd_YWrz4IDAAZSwSBUFQAkypVmHo5pbvp64cTDrZE73EYkEwJLGf0dRmedMFe2HiU3DiCr97K3I3KuufxYM_eMRIcn739dntxTq4QePtFdqYGWBzXWQutvvqxWQPbNi7PG_-aauEOzlwJiXG94C8t7NGu0SjB8xHf11Z3orf5Ni4-fRKugY8VJNBl39hnb4-d-g47ut7iuiFDkDHJzlSgt9LFq__CxShG_.YkL2w7QEU85VHjpOj5urieCr4-G"
},
"subTotal": 100.19,
"tax": 4.19
}
Below is the snippet of the code
import org.json.JSONObject;
import org.json.JSONArray;
public JSONObject constructCreateOrderPayload( String freedomPayPaymentKey,String orderInit_SessionKey, String payloadFile) {
String filepath = System.getProperty("user.dir")+"/src/test/resources/JsonFiles/"+payloadFile;
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
JSONObject jsonObject = new JSONObject(jsonContents);
JSONObject payment_obj = (JSONObject) jsonObject.get("payment");
payment_obj.put("paymentKey", freedomPayPaymentKey);
payment_obj.put("sessionKey",orderInit_SessionKey);
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println( " After Changes in JSON OBJECT : ");
System.out.println(jsonObject.toString());
System.out.println("");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
payload = jsonObject; // when i print the json boject the format is displaced hence when validated it says invalid json
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
return payload;
}
When I validated the Json after changes it shows as invalid with errors as shown in below snapshot
I tried a lot but no success, can somebody please look in to issue and advise me where I am going wrong or provide an solution this issue.
JSON in unordered, When you print jsonObject before making the changes you will know the order of the JSON is changed, I have used the Jackson Databind libraries and below is a working code, Change it accordingly
String filepath = "C:\\Users\\wilfred\\Desktop\\Input.json";
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(jsonContents);
System.out.println("Before converting : " + expected.toString());
JsonNode payment_obj = (expected.get("payment"));
((ObjectNode) payment_obj).put("paymentKey", "Trial1");
((ObjectNode) payment_obj).put("sessionKey", "Trial2");
System.out.println("After converting : " + expected.toString());
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
}
My approach was correct. The only mistake was i had not supply/pass on the correct values to few of the JSon attributes and that resulted in error response.
Rectified as per requirements and was able to get results correctly, hence closing this.
I am stuck in getting the data from the JSON file with multiple data sets.
{
"status": "ok",
"count": 3,
"count_total": 661,
"pages": 133,
"posts": [
{
"id": 20038,
"type": "post",
"slug": "xperia-launcher-download",
"url": "http:\/\/missingtricks.net\/xperia-launcher-download\/",
"status": "publish",
"title": "Download Xperia Launcher app for Android (Latest Version)"
},
{
"id": 94,
"type": "post",
"slug": "top-free-calling-apps-of-2014-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2014-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android November 2014"
},
{
"id": 98,
"type": "post",
"slug": "top-free-calling-apps-of-2016-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2016-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android December 2016"
}
]
}
I need to access the title, url and status from the above JSON file.
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
} catch (JSONException e) {
Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
I am getting a JSONException with the above code.
What should I do to access the title,status and url from the JSON File?
You have to fetch your JSONArray which is inside a JSONObject , so create a JSONObject and fetch your array with index "posts"
1.) result is a JSONObject so create a JSONObject
2.) Fetch your JSONArray with index value as "posts"
3.) Now simply traverse array objects by fetching it through index
JSONObject jObj = new JSONObject(result);
JSONArray jArray = jObj.getJSONArray("posts");
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
Note : i don't know weather it is a sample response with shorter version though your json object should ends with } not with , .
[{"id":20038,"type":"post","slug":"xperia-launcher-download","url":"http://missingtricks.net/xperia-launcher-download/","status":"publish","title":"Download
Xperia Launcher app for Android (Latest Version)",
// ^^^ there should be a } not a , to end json
// so make sure to do the correction so it will look like => ...st Version)"},
{"id":94,"type":"post","slug":"top-free-calling-apps-of-2014-year","url":"http://missingtricks.net/top-free-calling-apps-of-2014-year/","status":"publish","title":"Best
Free Calling Apps for Android November 2014", ]
Improvements :
you can use optString to avoid null or non-string value if there is no mapping key
This has two variations
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
fishData.status = json_data.optString("status","N/A");
// will return "N/A" if no key found
or To get empty string if no key found then simply use
fishData.status = json_data.optString("status");
// will return "" if no key found where "" is an empty string
You can validate your JSON here.
If entire JSON getJsonObject() is not working, then you should parse JSON objects & array in multiple arrays then use them.
This Is my first time with parsing JSON data. I am using the Google knowledge graph api. I got the api working and I can get the JSON result. This is Google 's sample return data for a sample query which I'm using now for testing.
{
"#context": {
"#vocab": "http://schema.org/",
"goog": "http://schema.googleapis.com/",
"resultScore": "goog:resultScore",
"detailedDescription": "goog:detailedDescription",
"EntitySearchResult": "goog:EntitySearchResult",
"kg": "http://g.co/kg"
},
"#type": "ItemList",
"itemListElement": [
{
"#type": "EntitySearchResult",
"result": {
"#id": "kg:/m/0dl567",
"name": "Taylor Swift",
"#type": [
"Thing",
"Person"
],
"description": "Singer-songwriter",
"image": {
"contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku",
"url": "https://en.wikipedia.org/wiki/Taylor_Swift",
"license": "http://creativecommons.org/licenses/by-sa/2.0"
},
"detailedDescription": {
"articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ",
"url": "http://en.wikipedia.org/wiki/Taylor_Swift",
"license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
},
"url": "http://taylorswift.com/"
},
"resultScore": 896.576599
}
]
}
So I want to parse it so that I can get the name, description, detailed description. This is my code but I always seem to get the exception. Any ideas why?
try {
JSONObject object=new JSONObject(gggg);
JSONArray itemListElement = object.getJSONArray("itemListElement");
for(int i=0; i < itemListElement.length();i++){
JSONObject c = itemListElement.getJSONObject(i);
JSONObject results = c.getJSONObject("result");
String name = results.getString("name").toString();
String description = results.getString("description").toString();
String detailedDescription = results.getString("articleBody").toString();
gggg = "Name: "+name+"\n Description: "+description+"\n "+detailedDescription;
}
responseView.append(gggg);
} catch (JSONException e) {
Toast.makeText(MainActivity.this,gggg,Toast.LENGTH_LONG).show();
}
Also the string gggg contains the JSON data. I don't know why but I am always getting the exception. Please tell me what is the error in my code and how to repair it.
Thanks.
"Name: Taylor Swift Description: Singer-songwriter Taylor Alison
Swift is an American singer-songwriter and actress. Raised in
Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the
age of 14 to pursue a career in country music. "
The problem is your String detailedDescription line.
You need to get the detailedDescription object before you retrieve the articleBody.
for(int i=0; i < itemListElement.length();i++){
JSONObject c = itemListElement.getJSONObject(i);
JSONObject results = c.getJSONObject("result");
String name = results.getString("name");
String description = results.getString("description");
JSONObject detailedDescription = results.getJSONObject("detailedDescription");
String articleBody = detailedDescription.getString("articleBody");
String x = "Name: "+name+"\n Description: "+description+"\n "+articleBody;
}
Also your .toString() method calls are redundant as you are calling .getString() on the JSON object.
With in the android json library it has a method called has element, which returns true or false. After successfully checking then access the element. The expection be caused by tring to access an element that isn't there.
Might be worth printing out after each time you create a new object to ensure that the objects are being created. It will also piont to where the expection is happening.
I hope someone can show me where i'm doing it wrong...
I'm using sendgrid for my email tracking and it is posting a JSON like the following:
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com"
"userid": "1123",
"template": "welcome"
}
]
Now i want to get the value of for example for "timestamp" which is 1337966815 . I've tried the following:
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
String jsonString = jb.toString();
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String timeStam = jsonObject.get(timestamp).toString();
The string of jsonString gives me the following which i think is in the right format:
[ { "email": "john.doe#sendgrid.com", "timestamp": 1337966815, "event": "click", "url": "http://sendgrid.com" "userid": "1123", "template": "welcome" }]
But i'm getting the following error at this line of code - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 52
What am I doing wrong? Is it the format of jsonString that is confusing the JsonObject?
Any help would be very much appreciated.
Kind regards
Francois
The JSON you show in both examples is invalid. There is a comma missing after "url":"http://sendgrid.com"
Ignoring that, the JSON you show is an array of JSON objects, not an object. This is what the [] denotes (correcting the missing comma):
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com",
"userid": "1123",
"template": "welcome"
}
]
If you are not mapping this JSON to a Java POJO, then you would want to use Gson's JsonParser to parse your String to a JsonElement (Note you could even use it to parse directly from the Stream, but this if for how you have your code now).
JsonElement je = new JsonParser().parse(jsonString);
Now you have what's called a "parse tree". This JsonElement is the root. To access it as an array you're going to do:
JsonArray myArray = je.getAsJsonArray();
You only show this array containing one object, but let's say it could have more than one. By iterating through the array you can do:
for (JsonElement e : myArray)
{
// Access the element as a JsonObject
JsonObject jo = e.getAsJsonObject();
// Get the `timestamp` element from the object
// since it's a number, we get it as a JsonPrimitive
JsonPrimitive tsPrimitive = jo.getAsJsonPrimitive("timestamp");
// get the primitive as a Java long
long timestamp = tsPrimitive.getAsLong();
System.out.println("Timestamp: " + timestamp);
}
Realize that Gson primarily is meant for Object Relational Mapping where you want to take that JSON and have it converted to a Java object. This is actually a lot simpler:
public class ResponseObject {
public String email;
public long timestamp;
public String event;
public String url;
public String userid;
public String template;
}
Because you have array of these, you want to use a TypeToken and Type to indicate your JSON is a List of these ResponseObject objects:
Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);
I'm trying to parse the spotify web-service response to get an artists' tracks which is like this:
{
"info": {
"num_results": 2974,
"limit": 100,
"offset": 0,
"query": "foo",
"type": "track",
"page": 1
},
"tracks": [
{
"album": {
"released": "2009",
"href": "spotify:album:1zCNrbPpz5OLSr6mSpPdKm",
"name": "Greatest Hits",
"availability": {
"territories": "AD AR AT AU BE BG BO BR CA CH CL CO CR CY CZ DE DK DO EC EE ES FI FR GB GR GT HK HN HU IE IS IT LI LT LU LV MC MT MX MY NI NL NO NZ PA PE PH PL PT PY RO SE SG SI SK SV TR TW US UY"
}
},
"name": "Everlong",
"popularity": "0.79",
"external-ids": [
{
"type": "isrc",
"id": "USRW29600011"
}
],
"length": 249.986,
"href": "spotify:track:07q6QTQXyPRCf7GbLakRPr",
"artists": [
{
"href": "spotify:artist:7jy3rLJdDQY21OgRLCZ9sD",
"name": "Foo Fighters"
}
],
"track-number": "3"
}]
}
I am using the Gson library to do this. So far I have tried this in my java code:
JsonParser parser = new JsonParser();
JsonObject jObject = parser.parse(jsonString).getAsJsonObject();
JsonArray jArray = jObject.get("tracks") .getAsJsonArray();
Gson gson = new Gson();
List<Track> trackArr = new ArrayList<Track>();
Type collectiontype = new TypeToken<Collection<Track>>(){}.getType();
Collection<Track> trackColl = gson.fromJson(jArray.toString(), collectiontype);
But I am getting the error : com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY
I don't understand why is it expecting begin object if I am doing "getAsJsonArray()" when trying to get the "tracks" object whihc in the json string is an array [].
The list of 'Track' was when I was doing this in a loop to get all the tracks into an array:
for (JsonElement jsonElement : jArray) {
Type collectiontype = new TypeToken<Collection<Track>>(){}.getType();
Collection<Track> trackCol = gson.fromJson(jsonElement, collectiontype);
trackArr.add((Track) trackCol);
}
What am I doind wrong here ?
I appreciate any guidance.
You don`t have to use extra library to parse a JSON file. Also use this link to read your JSON file in a human readable way.
Use the Native one as the following example:
Imports:
import org.json.JSONArray;
import org.json.JSONObject;
The code of parsing will be:
JSONObject fileJSONObject = new JSONObject(response);
JSONObject infoJSONObject = fileJSONObject.getJSONObject("info");
JSONArray tracksJSONArray = fileJSONObject.getJSONArray("tracks");
//Parsing the info
String trackType = infoJSONObject.getString("type");
String trackLimit = infoJSONObject.getString("limit");
//The rest of attributes
//Parsing the track list
JSONObject object;
for(int i=0;i<tracksJSONArray.length();i++){
object = tracksJSONArray.getJSONObject(i);
String trackName = object.getString("name");
//The rest of attributes
}
I recommend for you to Create a track class that contain all the needed attributes and their setter and getter and at the end of the parsing of each track create a new track.
I hope it helps
You can use my lib for solve this problem. For example you can do it.
private static List<Object> SpotifyTest()
{
InformationHandler informationHandler = null;
Injector injector = Guice.createInjector(new Module());
informationHandler = injector.getInstance(SpotifyService.class);
informationHandler.executeWithValue("la bamba");
return informationHandler.getDataModel();
}
The solution returns a List with a lot of HashMap where each key is a enumeration of key on service, the enumarator is:
public enum SpotifyKey
{
ALBUM_RELEASED,
ALBUM_HREF,
ALBUM_NAME,
ALBUM_AVAILABILITY,
NAME,
POPULARITY,
LENGTH,
HREF,
ARTIST_HREF,
ARTIST_NAME,
TRACK_NUMBER,
ID
}
Also you can view the code on github https://github.com/WeCodeMx/WCMPopularService/tree/develop