Generating any custom JSON in ABAP


You can use class ZCL_MDP_JSON Library that can encode/parse any JSON. JSON is supported natively in ABAP by the following features:

With the use of JSON-XML- it is known as special XML format that can be used for JSON data to be described using an XML representation. 

By defining a mapping between ABAP types and JSON. This is used in serializations and deserializations using the identity transformation ID.

As you can specify JSON data in different forms as an XML source in the statement CALL TRANSFORMATION and JSON can be specified as a target.

Check out the following sample code:

Example:

DATA text TYPE string VALUE `Hi JSON, ABAP here!`.
DATA writer TYPE REF TO cl_sxml_string_writer.
DATA json TYPE xstring.
“ABAP to JSON
writer =cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
CALL TRANSFORMATION id SOURCE text = text
   RESULT XML writer.
json = writer->get_output( ).
“JSON to ABAP
text =`{“TEXT”:”Hi ABAP, JSON here!”}`.
CALL TRANSFORMATION id SOURCE XML text
   RESULT text = text.

JSON/ABAP Serializer and Deserializer

In SAP ERP7.40, you have a simple transformation that can be used to convert ABAP to JSON and JSON to ABAP. This is most suitable when you require maximum performance and not worried about using Serializer and de-serializer.

You can also refer to the below link: 

https://wiki.scn.sap.com/wiki/display/Snippets/One+more+ABAP+to+JSON+Serializer+and+Deserializer

ABAP to JSON usage example:

DATA: lt_flight TYPE STANDARD TABLE OF sflight,
   lrf_descr TYPE REF TO cl_abap_typedescr,
   lv_json  TYPE string.
SELECT * FROM sflight INTO TABLE lt_flight.

* serialize table lt_flight into JSON, skipping initial fields and converting ABAP field names into camelCase
lv_json =/ui2/cl_json=>serialize( data = lt_flight compress = abap_true pretty_name = /ui2/cl_json=>pretty_mode-camel_case ).
WRITE / lv_json.
CLEAR lt_flight.

* deserialize JSON string json into internal table lt_flight doing camelCase to ABAP like field name mapping
/ui2/cl_json=>deserialize(EXPORTING json = lv_json pretty_name =/ui2/cl_json=>pretty_mode-camel_case CHANGING data = lt_flight ).

* serialize ABAP object into JSON string
lrf_descr = cl_abap_typedescr=>describe_by_data( lt_flight ).
lv_json =/ui2/cl_json=>serialize( lrf_descr ).
WRITE / lv_json.

Updated on: 05-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements