abap内表数据转JSON格式(两种方法)

2021-08-25 20:03发布


          点击此处--->   EasySAP.com 群内免费提供SAP练习系统(在群公告中)

加入QQ群:457200227(SAP S4 HANA技术交流) 群内免费提供SAP练习系统(在群公告中)

https://blog.csdn.net/champaignwolf/article/details/87981542


一:语法: CALL TRANSFORMATION id
DATA: lv_em  TYPE string,
        lv_em1 TYPE string.
  DATA: lt_but021  TYPE TABLE OF but021,
        lt_but0211 TYPE TABLE OF but021,
        ls_but021  TYPE but021.

  "数据
  lv_em = 'test' .

  ls_but021-partner = 'partner1' .
  ls_but021-adr_kind = 'kind1' .
  ls_but021-addrnumber = 'addr1' .
  APPEND ls_but021 TO lt_but021 .
  ls_but021-partner = 'partner2' .
  ls_but021-adr_kind = 'kind2' .
  ls_but021-addrnumber = 'addr2' .
  APPEND ls_but021 TO lt_but021 .

  "  abap 转json
  DATA(json_writer) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
  CALL TRANSFORMATION id
                      SOURCE content = lv_em
                             itable  = lt_but021
                      RESULT XML json_writer.
  DATA(json) = json_writer->get_output( ).
  DATA: lv_json TYPE string .
  CALL FUNCTION 'ECATT_CONV_XSTRING_TO_STRING'
    EXPORTING
      im_xstring  = json
      im_encoding = 'UTF-8'
    IMPORTING
      ex_string   = lv_json.


  "  json 转 abap
  CALL TRANSFORMATION id
                      SOURCE XML lv_json
                      RESULT content = lv_em1
                             itable = lt_but0211.
二:

  DATA lv_json TYPE string."定义JSON存放的变量
  DATA lr_json_serializer TYPE REF TO cl_trex_json_serializer."解析JSON 用到的类(编译成JSON格式)
  DATA lr_json_deserializer TYPE REF TO cl_trex_json_deserializer. "解析JSON 用到的类(解析JSON格式)

  DATA: BEGIN OF wa_wl,
          zzfld0000ht  TYPE crmt_item_descr_partner,
          zzfld0000hu  TYPE crmt_prshtextx_db,
          zzfld0000hv  TYPE zdtel00002x,
          zzfld0000hw  TYPE zdtel000135,
          zzfld0000hx  TYPE zdtel0001d3,
          zzfld0000i0  TYPE char10,
        END OF wa_wl.

 

      "根据结构通过这个类可以转换成JSON格式
      CREATE OBJECT lr_json_serializer
        EXPORTING
          data = wa_wl.
      lr_json_serializer->serialize( ).
      lv_json = lr_json_serializer->get_data( ).

      "OA 需要用双引号才能识别是JSON格式这里需要转换下
      REPLACE 'zzfld0000i0'IN lv_json WITH '"ZCBZ"'.
      REPLACE 'zzfld0000ht'IN lv_json WITH '"WLBM"'.
      REPLACE 'zzfld0000hu'IN lv_json WITH '"WLMC"'.
      REPLACE 'zzfld0000hw'IN lv_json WITH '"WLDJ"'.
      REPLACE 'zzfld0000hv'IN lv_json WITH '"WLSL"'.
      REPLACE 'zzfld0000hx'IN lv_json WITH '"HJ"'.

      IF i_num > 1.
        CONCATENATE  str1 ',' INTO str1.
      ENDIF.
      CONCATENATE  str1 lv_json INTO str1.

    IF str1 IS NOT INITIAL.
      CONCATENATE '[' str1 ']' INTO str1.
      CONDENSE str1 NO-GAPS.
      set_fieldcat 'RTFTEXTDYNAMIC' str1.
    ENDIF.
————————————————
版权声明:本文为CSDN博主「ChampaignWolf」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/champaignwolf/article/details/87981542

赞赏支持