How to read JSON file with Arrays and Objects in Java - java

I'm trying to read a file which is fetched from Opentdb and access data from only specific keys.
I've tried all of the given methods which includes GSON and Json Simple but ended up having errors.
Here's my JSON:
{
"response_code": 0,
"results": [
{
"category": "Sports",
"type": "multiple",
"difficulty": "easy",
"question": "Which of the following sports is not part of the triathlon?",
"correct_answer": "Horse-Riding",
"incorrect_answers": [
"Cycling",
"Swimming",
"Running"
]
},
{
"category": "Sports",
"type": "multiple",
"difficulty": "easy",
"question": "Which English football club has the nickname \u0026#039;The Foxes\u0026#039;?",
"correct_answer": "Leicester City",
"incorrect_answers": [
"Northampton Town",
"Bradford City",
"West Bromwich Albion"
]
},
I want to access only category, difficulty, question , correct_answer and incorrect_answers .

excample for you
try {
URL resource = App.class.getClassLoader().getResource("info.json");
System.out.println(resource.toString());
FileReader reader = new FileReader(resource.getFile());
// Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray infoList = (JSONArray) obj;
System.out.println(infoList);
Information i = new Information();
List<Information> info = i.parseInformationObject(infoList);
saveInformation(info);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
and
List<Information> parseInformationObject(JSONArray infoList) {
List<Information> in = new ArrayList<>();
infoList.forEach(emp -> {
JSONObject info = (JSONObject) emp;
String id = info.get("id").toString();
String state = info.get("state").toString();
String type = null;
if (info.get("type") != null) {
type = info.get("type").toString();
}
String host = null;
if (info.get("host") != null) {
host = info.get("host").toString();
}
long timestamp = (long) info.get("timestamp");
in.add(new Information(id, state, type, host, timestamp));
});
return in;
}

Related

how to remove json object from json Array using org.json.simple

I have a JSON file which is an JSON ARRAY with some JSON Objects and I want to remove the entire json Object if the value of longitude or latitude is an empty string "".
I am using the library org.json.simple. Here is my json file:
[ { "Longitude": 9.96233,
"Latitude": 49.80404 },
{
"Longitude": 6.11499,
"Latitude": 50.76891
},
{ "Longitude": 6.80592,
"Latitude": 51.53548
},
{
"Longitude": 9.50523,
"Latitude": 51.31991 },
{
"Longitude": ""
"Latitude": ""
},
{
"Longitude": 9.93368,
"Latitude": ""
},
{
"Longitude": 11.56122,
"Latitude": 48.14496
},
{
"Longitude": 13.34253,
"Latitude": 52.5319
},
{
"Longitude": 6.11327,
"Latitude": 50.77715
},
{
"Longitude": ""
"Latitude": ""
}
]
and here's where I am stuck. :
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader ("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
list.forEach(node -> {
String vari = (String)((JSONObject)node).get("longitude").toString();
if (vari==null) {
((JSONObject) node).remove();
System.out.println("deleted");
}
}
...
Any suggestions how can I change my code ?
You need to remove the node from the list but because of concurrent modification problem (modifying the list you are looping) you need another list.
I think it is easiest to collect into the new list all the nodes that qualify so like:
#SuppressWarnings("unchecked")
#Test
public void test() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray listNonNull = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>)list).forEach(node -> {
// here any check that qualifies the node like also checking "Latitude"
// Also no need to cast to a String
Object vari = node.get("Longitude");
if (vari != null && !vari.equals("")) {
listNonNull.add(node);
}
});
} catch (Exception e) {
throw e;
}
}
If you wish to use only the original list you can collect items to be removed to an another list and use it to remove nodes from the original list:
public void test2() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray toBeRemoved = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>) list).forEach(node -> {
Object vari = node.get("Longitude");
// here any check that qualifies the node like also checking "Latitude"
if (vari != null && !vari.equals("")) {
return; // not to be removed
}
toBeRemoved.add(node);
});
list.removeAll(toBeRemoved);
} catch (Exception e) {
throw e;
}
}
use .remove instead of .clear in the code.
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
ArrayList<JSONObject> objList = (ArrayList<JSONObject>) list.stream().filter(node -> {
String longitude = ((JSONObject) node).get("Longitude").toString();
String latitude = ((JSONObject) node).get("Latitude").toString();
if (longitude.isEmpty() || latitude.isEmpty()) {
return false;
}
return true;
}).collect(Collectors.toList());
} catch (IOException | ParseException 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());

Nested JSON response dynamically 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 is i can able to only create a 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;
}
}
You can do like this:
public class HotelMenu {
public static String crateHotelMenuJson(Statement stmt) throws Exception {
JSONArray hotels = new JSONArray();
JSONObject menu = new JSONObject();
String sql = "SELECT * FROM tb_hotel where Status='1'";
ResultSet hotelResultSet = stmt.executeQuery(sql);
while (hotelResultSet.next()) {
JSONObject hotel = new JSONObject();
hotel.put("id", hotelResultSet.getInt("Id"));
hotel.put("code", hotelResultSet.getString("Code"));
hotel.put("name", hotelResultSet.getString("Name"));
hotel.put("status", hotelResultSet.getString("Status"));
sql = "SELECT * FROM tb_subItem where Status='1' ";
ResultSet subItemResultSet = stmt.executeQuery(sql);
JSONArray subItems = new JSONArray();
while (subItemResultSet.next()) {
JSONObject hotelMenu = new JSONObject();
hotelMenu.put("id", subItemResultSet.getInt("Id"));
hotelMenu.put("name", subItemResultSet.getString("Name"));
hotelMenu.put("price", subItemResultSet.getString("Price"));
subItems.put(hotelMenu);
}
hotel.put("sub_items", subItems);
hotels.put(hotel);
}
menu.put("items", hotels);
JSONObject result = new JSONObject();
result.put("menu", menu);
return result.toString();
}}
I delete the try catch and finally code in order to make the logic more clear.
Don't make it so complex.
Assume you have a simple relation like below,
menu_items(hotel_name text, category text, item text, price number, status boolean)
Now you want to create a JSON response like below,
[
{
hotel : xyz,
menu : {
category : [
{
name : seaFood,
items : [
{
name : fish,
price : 100,
status : 1
},
{
name : friedFish,
price : 150,
status : 1
}
]
},
{
name : breads,
items : [
{
name : roti,
price : 50,
status : 1
},
{
name : naan,
price : 120,
status : 1
}
]
}
]
}
}
]
Generate the same like below code,
JSONArray hotels = new JSONArray();
String query = "SELECT * FROM menu_items where status=true order by hotel, category, item ";
ResultSet rs = stmt.executeQuery(query);
String prevHotel = null;
String prevCategory = null;
JSONObject hotel = null;
JSONObject menu = null;
JSONArray menuCategory = null;
JSONArray menuItems = null;
while (rs.next()) {
String hotelName = rs.getString("hotel_name");
if(prevHotel!=null && hotelName.equals(prevHotel)){
//Do nothing, as given hotel already exist
}else{
prevHotel = hotelName;
hotel = new JSONObject();
hotel.put("hotel", hotelName)
hotels.put(hotel);
menu = new JSONObject();
}
String category = rs.getString("category");
if(prevCategory!=null && prevCategory.equals(hotelName+category)){
//Do nothing, as given category already exist
}else{
prevCategory = hotelName+category;
menuCategory = new JSONArray();
menuCategory.put("name", category);
menu.put("category", menuCategory);
menuItems = new JSONArray();
menuCategory.put("items", menuItems);
}
JSONObject menuItem = new JSONObject();
menuItem.put("name", rs.getString("item"));
menuItem.put("price", rs.getString("price"));
menuItem.put("status", rs.getString("status"));
menuItems.put(menuItem);
}

Parsing Multiple Objects from a Single JSON File using JAVA

I have the following json file from which I am trying to extract data and store it to a database.
*//FirstBlockStart*
{
"_id": {
"$oid": "572395d8b1bf87f39645b94e"
},
"ReferenceDate": {
"$date": 1461949267500
},
"Url": "http://goTechhy.com",
"PublicationDate": {
"$date": 1461553200000
},
"LastUpdateDate": {
"$date": 1461553200000
},
}
//FirstBlockEnd
//SecondBlockStart
{
"_id": {
"$oid": "572394d8b1bf87f39645b94e"
},
"ReferenceDate": {
"$date": 1461969267500
},
"Url": "http://goTechhy.com",
"PublicationDate": {
"$date": 1461553200000
},
"LastUpdateDate": {
"$date": 1461353200000
},
}
//SecondBlockEnd
I need to extract the Oid, ReferenceData, PublicationData, LastUpdateDate from the JSON
Here is what I have tried.
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONObject Obj = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("E:\\Json2Db\\PlayStore1.json")));
//JSONObject Obj = (JSONObject) parser.parse(new FileReader("E:\\Json2Db\\PlayStore1.json"));
getAppID(Obj);
System.out.println(getAppID(Obj));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private static String getAppID(JSONObject obj) {
JSONObject appIDObj = (JSONObject) obj.get("_id");
String appID = (String) appIDObj.get("$oid");
return appID;
}
When I try to execute this code, I get the following error.
Unexpected token LEFT BRACE({) at position 4644.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:146)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
at com.freelancer.kaja.JsonParse.main(JsonParse.java:18)
But at the same time, When there is only One Block (say FirstBlock) in JSON, it works fine.. I am new to this JSON thing.. I dont know what I am missing here.. Please give your suggestions.
I would like the output to be something like this.
oid: 572395d8b1bf87f39645b94e
ReferenceDate:1461949267500
Url:http://goTechhy.com
PublicationDate:1461553200000
LastUpdateDate: 1461553200000
oid: 572395d8b1bf87f39645b94e
ReferenceDate:1461949267500
Url:http://goTechhy.com
PublicationDate:1461553200000
LastUpdateDate: 1461553200000

Android : Json Parsing show error

[
{
"description": "My home",
"name": "Sweet Home",
"point": {
"lat": 22.890976,
"long": 90.459097
},
"type": 1,
"cid": "5319197376176516414"
}
This is my json file for parsing information. Here is my code for parsing name and lng.
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.map)));
StringBuilder jsonBuilder = new StringBuilder();
try {
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String title = jsonObject.getString("name");
String lhg = jsonObject.getJSONObject("point").getString("lng");
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
}
}
It show's me an exception error while parsing json. How do i solve that? What was my problem?
Because "Point" in your JSON object never contains a property called "lng"
String lhg = jsonObject.getJSONObject("point").getString("lng")
it does contain one named "long"
"point": {
"lat": 22.890976,
"long": 90.459097
},
So the code to fetch the longitude should look like this:
String lhg = jsonObject.getJSONObject("point").getString("long")
String lhg = jsonObject.getJSONObject("point").getString("lng") use "long" instead of lng.

Categories

Resources