@fractastical Jsonify SObject


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // see: http://community.salesforce.com/t5/Apex-Code-Development/Building-a-reusable-JSON-component/m-p/172428
  2. // and: http://joe-ferraro.com/2009/04/extjs-vf-json/
  3.  
  4. public static String getJsonFromObject(String objectName, List<String> columns, String filterString)
  5. {
  6. if(filterString == null)
  7. filterString = '';
  8.  
  9. String jsonData = '[ ';
  10. try {
  11.  
  12. //System.debug('getJsonifiedObjectRecords for:' + objectName);
  13.  
  14. String queryString = 'Select id,';
  15.  
  16. for(String c: columns)
  17. queryString += c + ',';
  18.  
  19. queryString = queryString.substring(0,queryString.length() - 1);
  20. queryString += ' from ' + objectName + ' ' + filterString;
  21. queryString += ' limit 10000';
  22.  
  23. //System.debug('QUERYSTRING:' + objectName);
  24. List<sObject> sos = Database.query(queryString);
  25. //Map<String, Schema.SObjectField> columns = sos.getSObjectType().getDescribe().fields.getMap();
  26.  
  27. //jsonData += '[';
  28. for (sObject so : sos) {
  29. jsonData += ' { ';
  30. for(String column : columns)
  31. {
  32. System.debug('jsonData:' + jsonData);
  33. try
  34. {
  35. String cellval = '';
  36. List<String> cParts = column.split('[.]');
  37. if(cParts.size() == 2)
  38. {
  39. String outerObjectName = cParts.get(0);
  40. //if(outerObjectName.endsWith('__r'))
  41. // outerObjectName = outerObjectName.substring(0,outerObjectName.length() - 1) + 'c';
  42. cellval = (String) so.getSObject(cParts.get(0)).get(cParts.get(1));
  43. }
  44. else
  45. {
  46. cellVal = String.valueOf( so.get(column));
  47. }
  48. jsonData += '"'+column+'" : "'+cellVal+'",';
  49.  
  50.  
  51. }
  52. catch(Exception ex)
  53. {
  54. System.debug(ex);
  55. }
  56. }
  57. jsonData = jsonData.substring(0, jsonData.length() - 1);
  58. jsonData = jsonData + '},';
  59.  
  60. }
  61.  
  62. jsonData = jsonData.subString(0,jsonData.length() - 1);
  63.  
  64. }
  65. catch(Exception e)
  66. {
  67. System.debug('Bad query in Jsonify Call ' + e);
  68. }
  69.  
  70. jsonData += ']';
  71.  
  72. System.debug('jsonData:' + jsonData);
  73.  
  74. return jsonData;
  75. }
  76.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.