4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【ABAP】内部テーブルをJSONに変換する

Posted at

#やること
ABAPで「内部テーブルからJSONへの変換」と「JSONから内部テーブルへの変換」を行う。
方法は「CALL TRANSFORMATION」と「/UI2/CL_JSON」の2パターン。

#参考

#パターンA:「CALL TRANSFORMATION」を使用

##ソースコード

Y_TEST_JSON
  DATA lv_output_length TYPE i.
  DATA lt_binary_tab    TYPE STANDARD TABLE OF sdokcntbin.
  DATA lv_json          TYPE string.

  SELECT *
    FROM sflight
    INTO TABLE @DATA(lt_flightdata).

* (A-1)内部テーブルからJSONに変換
  DATA(lo_writer) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
  CALL TRANSFORMATION id SOURCE text = lt_flightdata RESULT XML lo_writer.
  DATA(lv_jsonx) = lo_writer->get_output( ).

  CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
    EXPORTING
      buffer        = lv_jsonx
    IMPORTING
      output_length = lv_output_length
    TABLES
      binary_tab    = lt_binary_tab.

  CALL FUNCTION 'SCMS_BINARY_TO_STRING'
    EXPORTING
      input_length  = lv_output_length
    IMPORTING
      text_buffer   = lv_json
      output_length = lv_output_length
    TABLES
      binary_tab    = lt_binary_tab.
  cl_demo_output=>display_json( lv_json ).

* (A-2)JSONから内部テーブルに変換
  CLEAR lt_flightdata.
  CALL TRANSFORMATION id SOURCE XML lv_jsonx RESULT text = lt_flightdata.
  cl_demo_output=>display( lt_flightdata ).

##実行結果
###(A-1)内部テーブルからJSONへの変換
cl_demo_outputの出力結果は以下
image.png

###(A-2)JSONから内部テーブルへの変換
cl_demo_outputの出力結果は以下
image.png

#パターンB:/UI2/CL_JSONを使用

##ソースコード

Y_TEST_JSON
  SELECT *
    FROM sflight
    INTO TABLE @DATA(lt_flightdata).

* (B-1)内部テーブルからJSONに変換
  DATA(lv_json) = /ui2/cl_json=>serialize( lt_flightdata ).
  cl_demo_output=>display_json( lv_json ).

* (B-2)JSONから内部テーブルに変換
  CLEAR lt_flightdata.
  /ui2/cl_json=>deserialize( EXPORTING json = lv_json CHANGING data = lt_flightdata ).
  cl_demo_output=>display( lt_flightdata ).

##実行結果
###(B-1)内部テーブルからJSONへの変換
cl_demo_outputの出力結果は以下
image.png

###(B-2)JSONから内部テーブルへの変換
cl_demo_outputの出力結果は以下
image.png

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?