使用ABAP将数据库查询结果转换为json / yaml / xml

时间:2018-07-31 10:33:18

标签: sap abap

是否可以使用ABAP将数据库查询结果转换为json / yaml / xml?

我是SAP软件开发的新手。

1 个答案:

答案 0 :(得分:4)

    DATA: lt_flight TYPE STANDARD TABLE OF sflight,
          lrf_descr TYPE REF TO cl_abap_typedescr,
          lv_json   TYPE string.

        SELECT * FROM sflight INTO TABLE lt_flight.

        * serialize table lt_flight into JSON, skipping initial fields and converting ABAP field names into camelCase
        lv_json = /ui2/cl_json=>serialize( data = lt_flight compress = abap_true pretty_name = /ui2/cl_json=>pretty_mode-camel_case ).
        WRITE / lv_json.

        CLEAR lt_flight.

* deserialize JSON string json into internal table lt_flight doing camelCase to ABAP like field name mapping
/ui2/cl_json=>deserialize( EXPORTING json = lv_json pretty_name = /ui2/cl_json=>pretty_mode-camel_case CHANGING data = lt_flight ).

* serialize ABAP object into JSON string
lrf_descr = cl_abap_typedescr=>describe_by_data( lt_flight ).
lv_json = /ui2/cl_json=>serialize( lrf_descr ).
WRITE / lv_json.

输出

[{"mandt":"000","carrid":"AA","connid":0017,"fldate":20130515,"price":422.94,"currency":"USD","planetype":"747-400","seatsmax":385,
"seatsocc":375,"paymentsum":192683.30,"seatsmaxB":31,"seatsoccB":31,"seatsmaxF":21,"seatsoccF":19},{"mandt":"000","carrid":"AA",
"connid....
{"ABSOLUTE_NAME":"\\TYPE=%_T00004S00000000O0000012480","ADMIN_TAB":"\\TYPE=%_T00004S00000000O0000012480",
"ADMIN_TAB_LINE":"\\TYPE=%_T00004S00000000O0000012480","DECIMALS":0,"HAS_UNIQUE_KEY":false,"INITIAL_SIZE":0,
"KEY":[{"NAME":"MANDT"},{"NAME":"CARRID"},{"NAME":"CO....

有关更多信息,请阅读Serializer and Deserializer

更新

另一个例子:

首先,您应该使用ABAPCL_SXML_STRING_WRITER创建Json as Type.到JSON Writer 然后调用转换将String转换为JSON格式的String。 最后一步是使用JSON检索Writer的输出。

DATA text TYPE string VALUE `Hello JSON, I’m ABAP!`.
DATA writer TYPE REF TO cl_sxml_string_writer.
DATA json TYPE xstring.

    “ABAP to JSON
    writer = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
    CALL TRANSFORMATION id SOURCE text = text
                            RESULT XML writer.
    json = writer->get_output( ).