There is a class that does just that: CL_TREX_JSON_SERIALIZER. The only thing it does not have (and SAP told me through a client message that they will not fix it, they do not support this code) puts the attribute in double quotes.
This is easy to install by adding line 52 to CL_TREX_JSON_SERIALIZER-RECURSE:
CONCATENATE '"' <abapcomp>-name '"' c_colon INTO l_value .
Program Example:
"We are going to serialize an error DATA: wa_error TYPE bapireturn. "Reference to the serializer DATA: cl_serializer TYPE REF TO zcl_trex_json_serializer. "Final output DATA: l_json_string TYPE string. wa_error-type = 'E'. wa_error-code = 'BC' . wa_error-message = 'This will serialize correctly.'. CREATE OBJECT cl_serializer EXPORTING DATA = wa_error. cl_serializer->serialize( ) . l_json_string = cl_serializer->get_data( ) . WRITE l_json_string.
I am using zcl_trex_json_serializer which is a cl_trex_json_serializer clone with the above fix. This code will return:
{"type": "E", "code": "BC", "message": "This will serialize correctly.", "log_no": "," log_msg_no ":" 000000 "," message_v1 ":", " message_v2 ":", "message_v3": "," message_v4 ":" "}
I used this code for structures containing tables, etc .; the code seems to be able to handle all of this.
source share