March 22, 2020
Estimated Post Reading Time ~

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. In this case, we can access the products from Magento using the below-explained method.

Note: In this example, the Magento API authorization is based on the 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 format which has a 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.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.