Monday 20 May 2019

How do we access the Magento product detail to AEM? - Magento AEM integration

There are cases where we need to access magento data to AEM. AEM By default supports magento plugin - AEM Extension to import data from Magento.

In some scenarios, Magento exposes the products over API's. In this case we can access the products from Magento using below explained method.

Note: In this example, the Magento API authorization is based on bearer token. The API response is in JSON format.

Java code - to invoke the API and access the products.

 //Create a HTTP connection management
 DefaultHttpClient httpClient = new DefaultHttpClient();

 //HttpGet helps posting client data the server.
 HttpGet getMagentoRequest = new HttpGet("Magento API url");

 //Add authorization token as part of request header
 getMagentoRequest.addHeader("Authorization", "Bearer TOKEN");

 //Invoke the API to retrieve response
 HttpResponse response = httpClient.execute(getMagentoRequest);

 //Read the response using buffered readerr
 BufferedReader magentoBr = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

 String retrievedResult;
 String resultString="" ;

 //capture the entire response in sting format
 while ((retrievedResult = magentoBr.readLine()) != null) {
                resultString = resultString + retrievedResult;
//Parse the JSON data present in the string format
JSONParser parse = new JSONParser();
//Type caste the parsed json data in json object
JSONObject jsonData = (JSONObject)parse.parse(resultString);

How to retrieve the JSON data?

Say we have below JSON fromat which has primary child and secondary child elements

    "id": "file",
    "value": "File",
    "popup": {
        "menuitem": [{
                "value": "New",
                "onclick": "CreateNewDoc()"

//get the individual item from JSON
String ID =  (String) jsonData.get( "id" );
//Now append ID on your bean class object

//Store the JSON object in JSON array as objects (For level 1 array element)

            JSONArray menuItems = (JSONArray) jobj.get("menuitem");
            for(int i=0;i<menuItems.size();i++)
            //Store the JSON objects in an array
            //Get the index of the JSON object and print the values as per the index
            JSONObject childItem = (JSONObject)menuItems.get(i);
            String value = (String) childItem.get("value");
            //Now append value on your bean class object
            String onclick = (String) childItem.get("onclick");
            //Now append onclick on your bean class object
Once we execute the code, we will have the parsed JSON Data available in Bean class.

Now in your HTL, iterate over the bean class objects and display the response.

No comments:

Post a Comment