SAP Tutorials Blog


{

"students": [{

"name": "Amar",

"age": 18,

"city": "Mumbai"

},

{

"name": "Akbar",

"age": 17,

"city": "Mumbai"

},

{

"name": "Anthony",

"age": 16,

"city": "Mumbai"

}

]

}


DATA : lv_string TYPE string VALUE '{"name": "Amar","age":18,"city": "Mumbai"}'.  

DATA(lo_reader) = cl_sxml_string_reader=>create( cl_abap_codepage=>convert_to( lv_json ) ).

TRY.

    lo_reader->next_node( ).

    lo_reader->skip_node( ).

    cl_demo_output=>display( 'JSON is valid' ).

  CATCH cx_sxml_parse_error INTO DATA(lx_parse_error).

    cl_demo_output=>display( lx_parse_error->get_text( ) ).

ENDTRY.


TYPES :

  BEGIN OF ty_student,

    name TYPE string,

    age  TYPE i,

    city TYPE string,

  END OF ty_student.


DATA : lv_json    TYPE string VALUE '{"name": "Amar","age":18,"city": "Mumbai"}',

       lr_data    TYPE REF TO data,

       ls_student TYPE ty_student.


/ui2/cl_json=>deserialize(

  EXPORTING

    json         = lv_json

    pretty_name  = /ui2/cl_json=>pretty_mode-user

    assoc_arrays = abap_true

  CHANGING

    data         = lr_data ).


IF lr_data IS BOUND.


  ASSIGN lr_data->* TO FIELD-SYMBOL(<lfs_data>).


  DO 3 TIMES. "Number of fields


    CASE sy-index.

      WHEN 1. DATA(lv_fname) = 'NAME'.

      WHEN 2. lv_fname = 'AGE'.

      WHEN 3. lv_fname = 'CITY'.

    ENDCASE.


    ASSIGN COMPONENT sy-index OF STRUCTURE ls_student TO FIELD-SYMBOL(<lfs_field>).

    ASSIGN COMPONENT lv_fname OF STRUCTURE <lfs_data> TO FIELD-SYMBOL(<lfs_ref_value>).

    IF <lfs_ref_value> IS ASSIGNED AND <lfs_field> IS ASSIGNED.

      lr_data = <lfs_ref_value>.

      ASSIGN lr_data->* TO FIELD-SYMBOL(<lfs_actual_value>).

      IF <lfs_actual_value> IS ASSIGNED.

        <lfs_field> = <lfs_actual_value>.

      ENDIF.

    ENDIF.

  ENDDO.


  cl_demo_output=>display( ls_student ).


ENDIF.


Serkan AKKAVAK

Computer Engineer BSc

SAP Department Manager

Contact : serkurumsal@yandex.com