javaaemsling

How to retrieve data from ContentFragment in AEM


I think there are 2 ways retrieve data from Content Fragment.

ContentFragment cf = resourceResolver.resolve(cfPath).adaptTo(ContentFragment.class);

cf.getElement("summary").getContent();                      // way1
cf.getElement("summary").getValue().getValue(String.class); // way2

When I need to get String value, are there any difference between way1 and way2? Which is better way?

Additional question:

When I need to get multiple values, is this only way to retrieve data from CF?

String[] array = cf.getElement("imagePaths").getValue().getValue(String[].class);

Solution

  • cf.getElement("summary").getContent(); 
    

    getContent() is return only string and if you have node value store which describe String/Text only then recommended to use.

     cf.getElement("summary").getValue();
    

    getValue() is returning FragmentData, which have option of multiple types to get value/values

    cf.getElement("summary").getValue().getValue();
    

    getValue() - which return Object (which you can cast) , getValue(T) - which return converted type T

    Nutshell - getContent() is recommended when you have only string/text type. if you have different types you can leverage getValue()