ABAP学习(25):内表数据生成JSON字符串
ABAP JSON格式字符串
ABAP内表表转换JSON字符串。
方式1:使用cl_trex_json_serializer和cl_trex_json_deserializer完成ABAP TO JSON,JSON TO ABAP互相转换。
方式2:使用CALL TRANSFORMATION这个语句实现转换。
示例:
"测试json字符串 FORM f_test_json. "方式1:这种转换key值没有双引号 DATA:lt_spfli TYPE TABLE OF spfli. DATA:ls_spfli LIKE LINE OF lt_spfli. "abap to json编码 DATA:lo_serialize TYPE REF TO cl_trex_json_serializer. "json to abap DATA:lo_deserialize TYPE REF TO cl_trex_json_deserializer. DATA:lv_json TYPE string. "abap to json SELECT * INTO TABLE lt_spfli FROM spfli. "实例化对象 CREATE OBJECT lo_serialize EXPORTING data = lt_spfli. "串行化 lo_serialize->serialize( ). lv_json = lo_serialize->get_data( ). WRITE:/ lv_json. "json to abap CLEAR lt_spfli[]. CREATE OBJECT lo_deserialize. lo_deserialize->deserialize( EXPORTING json = lv_json IMPORTING abap = lt_spfli ). LOOP AT lt_spfli INTO ls_spfli. WRITE:/ ls_spfli-carrid. ENDLOOP. "方式2:这种转换key值有双引号 "Transformation:ID,可以通过Tcode:STRANS查看,可以定义自己需要格式 TYPES:BEGIN OF s_fee, plan TYPE C LENGTH 10, cost TYPE P LENGTH 8 DECIMALS 2, percent TYPE C LENGTH 4, END OF s_fee. TYPES:BEGIN OF s_detail, f_type TYPE C LENGTH 2, date1 TYPE C LENGTH 8, date2 TYPE C LENGTH 8, END OF s_detail. DATA:lt_fee TYPE TABLE OF s_fee. DATA:ls_fee LIKE LINE OF lt_fee. DATA:lt_detail TYPE TABLE OF s_detail. DATA:ls_detail LIKE LINE OF lt_detail. "转换的类对象 DATA:lo_json_writer TYPE REF TO cl_sxml_string_writer. DATA:lv_json_x TYPE xstring. TYPES:s_line TYPE C LENGTH 255. DATA:lt_text TYPE TABLE OF s_line. DATA:ls_text LIKE LINE OF lt_text. DO 3 TIMES. ls_fee-plan = 'plan' && sy-index. ls_fee-cost = 10 * sy-index. ls_fee-percent = '12%'. APPEND ls_fee TO lt_fee. ls_detail-f_type = 'AA'. ls_detail-date1 = sy-datum + sy-index. ls_detail-date2 = sy-datum + sy-index. APPEND ls_detail TO lt_detail. ENDDO. lo_json_writer = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ). CALL TRANSFORMATION ID SOURCE fee = lt_fee detail = lt_detail RESULT XML lo_json_writer. lv_json_x = lo_json_writer->get_output( ). "abap to json CALL FUNCTION 'ECATT_CONV_XSTRING_TO_STRING' EXPORTING im_xstring = lv_json_x im_encoding = 'UTF-8' IMPORTING ex_string = lv_json. "将字符串拆分到table CALL FUNCTION 'SCMS_STRING_TO_FTEXT' EXPORTING text = lv_json TABLES ftext_tab = lt_text. LOOP AT lt_text INTO ls_text. WRITE:/ ls_text. ENDLOOP. "json to abap CLEAR lt_fee[]. CLEAR lt_detail[]. CALL TRANSFORMATION ID SOURCE XML lv_json RESULT fee = lt_fee detail = lt_detail. LOOP AT lt_detail INTO ls_detail. WRITE:/ ls_detail-f_type,ls_detail-date1,ls_detail-date2. ENDLOOP. LOOP AT lt_fee INTO ls_fee. WRITE:/ ls_fee-plan,ls_fee-cost,ls_fee-percent. ENDLOOP. ENDFORM.
本文来自博客园,作者:渔歌晚唱,转载请注明原文链接:https://www.cnblogs.com/tangToms/p/16025405.html