The following code is used to convert an ABAP object to JSON.

The compress parameter is set to X, the empty fields within the ABAP object will not be included in the generated JSON. If the entire JSON model is needed, the compress parameter can be left empty.

  
types: begin of ts_employee,
         id         type i,
         name       type string,
         last_name  type string,
         is_active  type abap_bool,
         department type string,
       end of ts_employee.

data : ls_employee  type ts_employee,
       lt_employees type standard table of ts_employee.

ls_employee-id = 32.
ls_employee-name = 'John'.
ls_employee-last_name = 'Smith'.
ls_employee-is_active = 'X'. "true
ls_employee-department = 'IT'. 
append ls_employee to lt_employees.
clear ls_employee.

ls_employee-id = 22.
ls_employee-name = 'Emily'.
ls_employee-last_name = 'Johnson'.
ls_employee-is_active = '-'. "false
append ls_employee to lt_employees.
clear ls_employee.


data(lv_json) = /ui2/cl_json=>serialize( 
                                data = lt_employees
                                pretty_name = /ui2/cl_json=>pretty_mode-camel_case
                                compress = 'X'
                                        ).
  

Output:

  
[
  {
    "id": 32,
    "name": "John",
    "lastName": "Smith",
    "isActive": true,
    "department": "IT"
  },
  {
    "id": 22,
    "name": "Emily",
    "lastName": "Johnson",
    "isActive": false
  }
]
  

The following code is used to give specific names to field names in JSON.

  
data : lt_mappings type /ui2/cl_json=>name_mappings,
       ls_mapping  like line of lt_mappings.

ls_mapping-abap = 'last_name'.
ls_mapping-json = 'Last Name'.
append ls_mapping to lt_mappings.
clear ls_mapping.
    
data(lv_json) = /ui2/cl_json=>serialize( 
                                data = lt_employees
                                pretty_name = /ui2/cl_json=>pretty_mode-camel_case
                                compress = 'X'
                                name_mappings = lt_mappings
                                        ).
  

Output:

  
[
  {
    "id": 32,
    "name": "John",
    "Last Name": "Smith",
    "isActive": true
  },
  {
    "id": 22,
    "name": "Emily",
    "Last Name": "Johnson",
    "isActive": false
  }
]