嵌套的JSON响应在java中动态生成

时间:2017-01-16 10:42:21

标签: java json

我需要创建一个类似下面的json响应。我尝试了一些代码,但无法得到我需要的东西。在java代码中需要帮助来创建嵌套数组,以根据类别以及类别详细信息对食品进行分组,如下面的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"
    }]
}
]
}
}

到目前为止我尝试的是我只能在一个阵列中创建一个响应

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

2 个答案:

答案 0 :(得分:0)

你可以这样做:

dateByAddingTimeInterval

我删除了try catch和finally代码,以使逻辑更清晰。

答案 1 :(得分:0)

不要让它如此复杂。 假设你有一个简单的关系,如下所示,

  

menu_items(hotel_name文本,类别文本,项目文本,价格编号,状态布尔值)

现在您要创建如下所示的JSON响应,

[
{
    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
                    }
                ]
            }
        ]
    }
}
]

生成相同的代码,

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