Nested JSON Array in Java - 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());

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

How to work with json object and jsonarray

I have this JSON response:
"objects":{
"5": [
[
{
"id_lot_espace": 0,
"id_lot_objet": "0",
"id_objet_piece": 0,
"params": {
"auto": "1",
"objLink": "0",
"setpointM": "7",
"setpoint0": "21",
"setpoint1": "19",
"setpointA": "16",
"tempSocialJ": "19",
"tempSocialN": "17",
"tempMin": "7",
"tempMax": "30",
"tempFrom": "2018-10-15",
"tempTo": "2019-04-15"
},
"label": "migo",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "zwave_device_fab36177_node6_thermostat_setpoint_heating",
"renommable": "0",
"id_famille": 5,
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
]
],
"17": {
"381": {
"19": {
"id_lot_espace": "381",
"id_lot_objet": "0",
"id_objet_piece": "19",
"params": "",
"label": "Pièce principale - Tête thermostatique",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "",
"renommable": "0",
"id_famille": "17",
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
}
}
}
}
I want to access pieceLabel in each element. Here’s what I’ve tried so far:
job = new JSONObject(responseContent);
JSONObject object = job.getJSONObject("objects");
Iterator<String> it = object.keys();
while (it.hasNext()) {
String key = it.next();
JSONObject obj1 = object.getJSONObject(key);
Iterator<String> it1 = obj1.keys();
while (it1.hasNext()) {
String key1 = it1.next();
JSONObject obj2 = obj1.getJSONObject(key1);
Iterator<String> it2 = obj2.keys();
while (it2.hasNext()) {
String key2 = it2.next();
final JSONObject obj3 = obj2.getJSONObject(key2);
String pieceLabel = String.valueOf(obj3.get("pieceLabel"));
}
}
}
Please check your json its having issue. You can use many tools online to check your json if its proper or not.
I usually use https://codebeautify.org/jsonviewer
Corrected Json
[
[
{
"id_lot_espace": 0,
"id_lot_objet": "0",
"id_objet_piece": 0,
"params": {
"auto": "1",
"objLink": "0",
"setpointM": "7",
"setpoint0": "21",
"setpoint1": "19",
"setpointA": "16",
"tempSocialJ": "19",
"tempSocialN": "17",
"tempMin": "7",
"tempMax": "30",
"tempFrom": "2018-10-15",
"tempTo": "2019-04-15"
},
"label": "migo",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "zwave_device_fab36177_node6_thermostat_setpoint_heating",
"renommable": "0",
"id_famille": 5,
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
]
]
{
"17": {
"381": {
"19": {
"id_lot_espace": "381",
"id_lot_objet": "0",
"id_objet_piece": "19",
"params": "",
"label": "Pièce principale - Tête thermostatique",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "",
"renommable": "0",
"id_famille": "17",
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
}
}
}
Final Code
try {
JSONObject jObject = new JSONObject(sss.trim());
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
Log.d("vt","output1 "+key);
JSONObject obj1 = jObject.getJSONObject(key);
Iterator<String> it1 = obj1.keys();
while (it1.hasNext()) {
String key1 = it1.next();
Log.d("vt","output2 "+key1);
JSONObject obj2 = obj1.getJSONObject(key1);
Iterator<String> it2 = obj2.keys();
while (it2.hasNext()) {
String key2 = it2.next();
Log.d("vt","output3 "+key2);
final JSONObject obj3 = obj2.getJSONObject(key2);
String pieceLabel = String.valueOf(obj3.get("pieceLabel"));
Log.d("vt","final "+pieceLabel);
}
}
}
}catch (Exception e){
Log.d("vt","error "+e.getMessage());
}
You need to iterate your unstructured json recursively and check every key.
Here is a working example to show you how to achieve what you want to do:
public class Main {
private static List<String> values = new ArrayList();
public static void main(String[] args) {
try {
JSONObject jsonObject = new JSONObject(new String(Files.readAllBytes(Paths.get("test.json"))));
findValues(jsonObject);
values.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void findValues(Object root) {
if (root instanceof JSONObject) {
Iterator<String> keys = ((JSONObject)root).keys();
while (keys.hasNext()) {
String key = keys.next();
if ("pieceLabel".equals(key)) {
values.add(((JSONObject)root).getString(key));
}
else {
Object o = ((JSONObject)root).get(key);
findValues(o);
}
}
}
else if (root instanceof JSONArray) {
for (Object o : (JSONArray)root) {
findValues(o);
}
}
}
}
test.json file contains your example json.
Output is :
Pièce principale
Pièce principale
Change the values and order of keys and see the result.
I passed your json through https://jsoneditoronline.org and did not find any error.
I used json-simple which can be found here:
https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1
My example is below with no loops.
public static void main( String[] args ) {
JSONParser parser = new JSONParser();
JSONObject jobj = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(".json"),"UTF-8"));
jobj = (JSONObject) parser.parse(reader);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
JSONObject jobj2 = (JSONObject) jobj.get("object"); // outer object.
JSONObject jobj3 = (JSONObject) jobj2.get("17"); // nested object.
JSONObject jobj4 = (JSONObject) jobj3.get("381"); // nested object.
JSONObject jobj5 = (JSONObject) jobj4.get("19"); // nested object.
System.out.println(jobj5.get("pieceLabel")); // Returns the value to where the specified key is mapped.
JSONArray jsarry = (JSONArray) jobj.get("5"); // Json Array.
JSONArray jsarry2 = (JSONArray) jsarry.get(0); // nested Json Array.
JSONObject nestedjsobj = (JSONObject) jsarry2.get(0); // nested object.
System.out.println(nestedjsobj.get("pieceLabel")); // Returns the value to where the specified key is mapped.
}
output:
Pièce principale
Pièce principale

How to name a JSON?

This is my code
List<Object[]> list = query.list();
List<JSONObject> result = new ArrayList<>();
for (Object[] rows : list) {
String buildingId = rows[0].toString();
String floorId = rows[1].toString();
String routerId = rows[2].toString();
String routerName = rows[3].toString();
Map<String, List<String>> floorMap = buildingMap.get(buildingId);
if(floorMap == null) {
floorMap = new HashMap<>();
}
......
}
What i need JSON format is like this
"buildings":{
"building_id":"3"={
"floor_id":"21"=[
"router_id":"3"
]
},
"building_id":"2"={
"floor_id":"20"=[
"router_id":"1101",
"router_id":"1102",
"router_id":"0",
"router_id":"1104",
"router_id":"1106"
],
"floor_id":"17"=[
"router_id":"1111",
"router_id":"1112",
"router_id":"1113"
]
},
"building_id":"1"={
"floor_id":"10"=[
"router_id":"1"
]
}
}
But now i'm getting like this
{
3={
21=[
3
]
},
2={
20=[
1101,
1102,
0,
1104,
1106
],
17=[
1111,
1112,
1113,
]
},
1={
10=[
1
]
}
}
thanks in advance
List<Object[]> list = query.list();
Gson gson = new Gson();
// convert your list to json
String jsonList = gson.toJson(list);
you need Gson Jar and simply you can convert list into json string.
My senior gave this code and finally it worked for me
`#Override
public String getFullRouterList() throws Exception {
//Format
// -- building map with building_id and floor map
// -- floor map with floor_id and list of routers
Map<String, Map<String, List<String>>> buildingMap = new HashMap<>();
System.out.println("in dao of getFullRouterList ");
session = sessionFactory.openSession();
tx = session.beginTransaction();
String sql = "SELECT building_id, floor_id, router_id, router_name FROM iot_trackbit.router_details";
SQLQuery query = session.createSQLQuery(sql);
List<Object[]> list = query.list();
List<JSONArray> result = new ArrayList<>();
for (Object[] rows : list) {
String buildingId = rows[0].toString();
String floorId = rows[1].toString();
String routerId = rows[2].toString();
String routerName = rows[3].toString();
Map<String, List<String>> floorMap = buildingMap.get(buildingId);
if(floorMap == null) {
floorMap = new HashMap<>();
}
List<String> routerList = floorMap.get(floorId);
if(routerList == null) {
routerList = new ArrayList<>();
}
routerList.add(routerId);
floorMap.put(floorId, routerList);
buildingMap.put(buildingId, floorMap);
System.out.println(buildingMap.keySet());
System.out.println(buildingMap);
}
JSONObject finalObj = new JSONObject();
JSONArray buildingsArr = new JSONArray();
for(String buildingId : buildingMap.keySet()) {
JSONObject buildingObject = new JSONObject();
Map<String, List<String>> floorMap = (HashMap<String, List<String>>) buildingMap.get(buildingId);
//{"1":["router1","router2","router3"]}
JSONArray floorsArr = new JSONArray();
for(String floorId : floorMap.keySet()) {
JSONObject floorObject = new JSONObject();
List<String> routerList = floorMap.get(floorId);
//["router1","router2"]
JSONArray array = new JSONArray();
for(String routerId : routerList) {
JSONObject routerObj = new JSONObject();
routerObj.put("id",routerId);
array.add(routerObj);
}
floorObject.put("id",floorId);
floorObject.put("routers", array);
floorsArr.add(floorObject);
}
buildingObject.put("id", buildingId);
buildingObject.put("floors", floorsArr);//floors array
buildingsArr.add(buildingObject);
finalObj.put("buildings",buildingsArr);
}
System.out.println("finalObj.toJSONString() : " +finalObj.toJSONString());
tx.commit();
session.close();
return finalObj.toJSONString();
}`
Now im geting like this format
{
"buildings": [
{
"id": "3",
"floors": [
{
"id": "21",
"routers": [
{
"id": "3"
}
]
},
{
"id": "23",
"routers": [
{
"id": "0"
},
{
"id": "gateway123"
},
{
"id": "1001"
},
{
"id": "1002"
},
{
"id": "1003"
}
]
}
]
},
{
"id": "2",
"floors": [
{
"id": "20",
"routers": [
{
"id": "1101"
},
{
"id": "1102"
},
{
"id": "0"
},
{
"id": "1104"
},
{
"id": "1106"
},
{
"id": "1107"
},
{
"id": "1111"
},
{
"id": "1109"
},
{
"id": "1110"
}
]
},
{
"id": "17",
"routers": [
{
"id": "1111"
},
{
"id": "1112"
},
{
"id": "1113"
},
{
"id": "1114"
},
{
"id": "1115"
},
{
"id": "1116"
},
{
"id": "1117"
},
{
"id": "1118"
},
{
"id": "g1"
},
{
"id": "1119"
},
{
"id": "0"
}
]
},
{
"id": "18",
"routers": [
{
"id": "010101"
},
{
"id": "0"
}
]
}
]
},
{
"id": "1",
"floors": [
{
"id": "10",
"routers": [
{
"id": "1"
}
]
}
]
}
]
}`
Thanks for all

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

JSON content from file via 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?

Categories

Resources