0

Want to create a class that can convert any json to HTML in a tabular form. Just like http://any-json2html.lkatney.com/. We have the source code in javascript as well (https://github.com/lkatney/ANY-JSON2HTML/blob/master/scripts/json.htmTable.js). I'm not sure how we can proceed. Here is the piece of code that i have written taking the given source code as reference.

public class JsonToHTML {
    public static void createTableView(){
        Map<String, Object> parsedJson = (Map<String, Object>)JSON.deserializeUntyped('{"Name":"S","children":[{"title":"D"}]}');
        System.debug(parsedJson);
        Boolean found =false;
        Boolean enableHeader = true;
        Boolean firstTableFound = false;
        String str = '';
        String theme = 'lightPro';
        Integer row = 0;
        Integer count = 0;
        if(firstTableFound){ //defined false on line 7 so else will be executed
            str += '<div class="scrollable-table"><table class="' + theme + '">';  // As per the DOM it set table
         }else{
            str += '<table class="' + theme + '">'; // adding the theme to table
            found = true;
            firstTableFound = true;
         }
         str += '<tbody>';   // after table  As per the DOM it set body
        for(String key : parsedJson.keySet()){
            Object value = parsedJson.get(key);
            System.debug(key);
            System.debug(value);
            row++;
            count++;
             str += (math.mod(row,2) == 0) ? '<tr class="alt">' : '<tr>'; 
              if (enableHeader) {
                str += '<th scope="row">' + count + '</th>'; 
             }
             str += '<td>' + value + '</td>';
             str += '</tr>';
             str += '</tbody>';
              str += '</table>';
        }
        System.debug(str);
    }
}
  • 1
    What are you trying to accomplish at the end of the day (sounds like an XY Problem)? Creating HTML code via Apex could probably be avoided if you try using something like lightning-datatable or something similar. There's lot of options across the different technologies Salesforce offers (Visualforce pages, Aura components, Lightning Web Components, etc) that should avoid producing HTML code within Apex itself – Brian Miller Dec 2 '19 at 8:41
  • @BrianMiller That makes sense but my requirement is to collect an json response and show it in a table format to an end user. * i cant use lightning components here – Dadhich Sourav Dec 2 '19 at 8:55
  • 1
    You could "separate the concerns" by moving the HTML generation part out to Visualforce or to an LWC and so benefit from the templating features of either. – Keith C Dec 2 '19 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.