-1

orderHDRObjectList contains hdrObject table deatils and orderDETObjList contains orderDetails table list this is a valid jason and i want to implement this.

and display orderHdrObjList of orderId=1 and corresponding orderDETObjList of orderId=1 and so on..

how can I do that?

{
    "orderObj": {
        "orderHDRObjList": {
            "hdrObject": [{
                    "orderID": 1,
                    "customerName": "Alex",
                    "address": "Kottayam",
                    "totalPrice": 250,
                    "orderDate": "2020-11-21"
                },
                {
                    "orderID": 2,
                    "customerName": "Aljin",
                    "address": "Kochi",
                    "totalPrice": 250,
                    "orderDate": "2020-11-21"
                }
            ]
        },
        "orderDETObjList": {
            "1": [{
                    "productId": 2,
                    "productQty": 250,
                    "price": 500
                },
                {
                    "productId": 3,
                    "productQty": 150,
                    "price": 300
                }
            ],
            "2": [{
                    "productId": 2,
                    "productQty": 250,
                    "price": 500
                },
                {
                    "productId": 3,
                    "productQty": 150,
                    "price": 300
                }
            ]
        }
    }
}
Kevin
  • 5
  • 4
  • 1
    if you mean reading json in java you can use `JSONObject` or `JSONArray` classes see: https://www.tutorialspoint.com/json/json_java_example.htm – MMD Nov 23 '20 at 07:51
  • no..i meant how to put datas from databse like this json structrue . – Kevin Nov 23 '20 at 08:02
  • Do you mean getting data from database and then convert them to a json? – MMD Nov 23 '20 at 08:22
  • yes. how do i do that? i want it in this structure though. its from 2 tables – Kevin Nov 23 '20 at 08:54
  • here I posted your answer please let me know if you need more information. good luck :) – MMD Nov 23 '20 at 09:31

1 Answers1

0

solution 1: use jackson explained here for converting your model to json: Converting Java objects to JSON with Jackson

solution 2: use java classes: JSONObject and JSONArray

*needs

import org.json.JSONArray;
import org.json.JSONObject;

e.g:

JSONObject json = new JSONObject();
json.put("key1", "value1");

JSONArray array = new JSONArray();
array.put(1);
array.put(2);

json.put("numbers", array);

the output will be this

{
    "key1": "value1",
    "numbers": [
        1,
        2
    ]
}

to convert your java json object to a string use toString() method

System.out.println(json.toString());

some IDEs like IntelliJ suggests to put your json codes inside a try...catch because it may produce some Exceptions when you want to read data with a wrong index.

MMD
  • 521
  • 5
  • 14