ABAP 内表与JSON转换

一、内表转JSON

"-----------------------------@斌将军-----------------------------
TYPES: BEGIN OF ty_name_mapping,
         abap TYPE abap_compname,
         json TYPE string,
       END OF ty_name_mapping.

TYPES:BEGIN OF ty_makt,
        matnr TYPE makt-matnr,
        spras TYPE makt-spras,
        maktx TYPE makt-maktx,
      END OF ty_makt.

DATA:gt_makt TYPE TABLE OF ty_makt,
     gs_makt TYPE ty_makt.

DATA:ls_mappings TYPE ty_name_mapping,
     lt_mappings TYPE HASHED TABLE OF ty_name_mapping WITH UNIQUE KEY abap.
DATA:lv_json TYPE string.

"填充内表数据
SELECT
  matnr
  spras
  maktx
FROM makt
INTO TABLE gt_makt
WHERE spras = sy-langu.

"获取表结构字段
*SELECT
*  tabname,
*  fieldname
*FROM dd03l
*INTO TABLE @DATA(lt_dd03l)
*WHERE tabname = 'MAKT'
*  AND as4local = 'A'.

*LOOP AT lt_dd03l INTO DATA(ls_dd03l).
*  CLEAR:ls_mappings.
*  ls_mappings-abap = ls_dd03l-fieldname.
*  ls_mappings-json = ls_dd03l-fieldname.
*  TRANSLATE ls_mappings-json TO LOWER CASE.
*  INSERT ls_mappings INTO TABLE lt_mappings.
*ENDLOOP.

"内表的字段为大写,转成JSON的键需要小写,
*"在转换时配置字段映射
*"获取内表结构字段
*DATA(lo_table_basic) = CAST cl_abap_tabledescr( cl_abap_tabledescr=>describe_by_data( gt_makt ) ).
*DATA(lo_struct_basic) = CAST cl_abap_structdescr( lo_table_basic->get_table_line_type( ) ).
*DATA(lt_dd03l) = lo_struct_basic->get_components( ).
*
*"配置内表字段与JSON键的映射
*LOOP AT lt_dd03l INTO DATA(ls_dd03l).
*  CLEAR:ls_mappings.
*  ls_mappings-abap = ls_dd03l-name.
*  ls_mappings-json = ls_dd03l-name.
*  TRANSLATE ls_mappings-json TO LOWER CASE.
*  INSERT ls_mappings INTO TABLE lt_mappings.
*ENDLOOP.
DATA:lv_pre_name  TYPE char1.
  lv_pre_name = 'L'."JSON键为小写
"内表转JSON
lv_json = /ui2/cl_json=>serialize( data = gt_makt pretty_name = lv_pre_name name_mappings = lt_mappings ).

WRITE:lv_json.
"-----------------------------@斌将军-----------------------------

二、JSON转内表

"-----------------------------@斌将军-----------------------------
"JSON转内表
REFRESH:gt_makt.
/ui2/cl_json=>deserialize( EXPORTING json = lv_json
                                      pretty_name = /ui2/cl_json=>pretty_mode-camel_case
                            CHANGING data = gt_makt ).
"-----------------------------@斌将军-----------------------------

 

定期更文,欢迎关注

 
posted @ 2022-06-14 11:43  斌将军  阅读(311)  评论(0编辑  收藏  举报