Why do I always get JSON Exception? - java
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.
Related
Not sure why it has to say not valid Json after replacing the values of paymentKey and Session key
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.
Get all records from JSON response
I'm still kind of new to the Rest Assured API world. I've read through as much documentation on https://github.com/rest-assured/rest-assured/wiki/Usage#example-3---complex-parsing-and-validation as I can stand. I have a response that looks like: { "StatusCode": 200, "Result": [ { "EmployeeId": "5661631", "PhoneTypeDescription": "Home", "PhoneNumber": "9701234567", }, { "EmployeeId": "5661631", "PhoneTypeDescription": "mobile1", "PhoneNumber": "2531234567", }, { "EmployeeId": "5661631", "PhoneTypeDescription": "mobile2", "PhoneNumber": "8081234567", } ] } I've been struggling with how to get just the first record's PhoneNumber. String responseBody= given() .relaxedHTTPSValidation().contentType("application/json") .param("api_key", api_key). when() .get("/api/employees/" + employeeId) .andReturn().asString(); JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result"); phoneNumber = jsonPath.getString("PhoneNumber"); I get all the phone numbers in this case: phoneNumber = "[9701234567,2531234567,8081234567]" How can I get just the first record? I'd rather not have to perform string operations to deal with the, "[". Thanks
You can simply do, JSONObject json = new JSONObject(responseBody); phoneNumber = json.getJSONArray("Result").getJSONObject(0).getString("PhoneNumber"); Here, 0 indicates the first record in the JSON Array Result.
Because you know the index of the element you want to retrieve, you can use the following code: JsonPath jsonPath = new JsonPath(response); String phoneNumber = jsonPath.getString("Result[0].PhoneNumber");
unable to parse the json in my java program
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
Parsing JSON data in Java for Android
I hope someone might be able to help me. I am trying to parse following json file: {"seminar":[ {"categoryid": "1","cpe": "13","inventory":["Discussion","Value x","Value y" ],"teachers": [ { "titel": "Dipl.-Ing.", "company": "XY", "name": "Test", "id": "3", } ], },... I am lost with parsing the teachers data in... ... private static final String TAG_teachers = "teachers"; private static final String TAG_TITLE = "title"; for(int i = 0; i < seminar.length(); i++){ JSONObject c = seminar.getJSONObject(i); ... teachers = c.getJSONArray(TAG_DOZENTEN); for(int z = 0; z < teachers.length(); z++){ JSONObject d = teachers.getJSONObject(z); String title = d.getString(TAG_TITLE); Log.d("JSONParsingActivity", title); I get the error System.err(1010): org.json.JSONException: Value null at teachers of type org.json.JSONObject$1 cannot be converted to JSONArray. What did I do wrong? As I understand from the JSON documentation, teachers is an JSON Array and not an Object. Is somebody able to help me?
You have an extra (trailing) comma in teachers (after "3"). Not allowed in JSON. Remove it and see if that helps.
If your JSON is really of the form: { ... }, { ... }, { ... }, ... This is invalid JSON The root enclosure must either be a single object (in {}) or an array (in []). If your intent is to send an array of objects, then simply wrap the entire thing with square brackets to make it an array and create a JSONArray object from it. So it must be like this [ { ... }, { ... }, { ... }, ... ] You also need to make sure that you don;t have extra commas, unclosed brackets, etc. Use JSONLint or other similar JSON format checker to save yourself some time in finding syntax problems.
Best way to get a list of countries in Java
Other than Locale.getISOCountries() that is, because I'm already getting some strange errors with that. What else is the best way to get the 2-letter country codes as well as the full country name?
See code snippets : String[] countryCodes = Locale.getISOCountries(); for (String countryCode : countryCodes) { Locale obj = new Locale("", countryCode); System.out.println("Country Code = " + obj.getCountry() + ", Country Name = " + obj.getDisplayCountry()); } Refer to this country list in Java for more examples.
For a separate project, I took the country code data from the ISO site. Beware of the following: The names are in all caps. You will probably want to tweak it so it's not. The names are not all in simple ASCII. The names are not entirely political neutral (it is probably impossible for any purported list of countries to be). E.g., "Taiwan, Province of China" is a name. A good starting point to learn about the issues is this blog post.
Create a Map out of this page http://www.theodora.com/country_digraphs.html Save it to a file (I suggest XMLEncoder/XMLDecoder class) Create a wrapping class that loads this Map from the file (I'd use a lazily initialized singleton) and allows access to the get(...) methods. Repeat (or use a bi-directional map) these steps for each column of the table on the afore mentioned webpage. Fancy-Time: Throw in some code to wrap the entries in a Reference object (SoftReference?) so that the Map won't throw MemoryErrors
You can use from json bellow like Json parsing.. String jsonString =JSON_DATA; ObjectMapper mapper = new ObjectMapper(); try { JsonNode rootNode = mapper.readTree(jsonString); for (JsonNode node : rootNode) { String countrycode = node.path("code").asText(); String dialnumber = node.path("dial_code").asText(); String countryname = node.path("name").asText(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Json String here public static String JSON_DATA=" [ { "name": "Afghanistan", "dial_code": "+93", "code": "AF" }, { "name": "Aland Islands", "dial_code": "+358", "code": "AX" }, { "name": "Albania", "dial_code": "+355", "code": "AL" }, { "name": "Algeria", "dial_code": "+213", "code": "DZ" }, { "name": "AmericanSamoa", "dial_code": "+1684", "code": "AS" }]"; Or You can download full json from link : https://gist.github.com/Goles/3196253