abap-json 数据解析和转换

1. 系统标准方法

    /ui2/cl_json=>deserialize(
       EXPORTING
         json            = json
       CHANGING
         data            = data
           ).
    json = /ui2/cl_json=>serialize( data             = data ).
DATA: deserializer TYPE REF TO cl_trex_json_deserializer.
    CREATE OBJECT deserializer.
    deserializer->deserialize(
      EXPORTING
        json    = json
      IMPORTING
         abap   = abap
       ).
          DATA: serializer TYPE REF TO cl_trex_json_serializer.
          CREATE OBJECT serializer
            EXPORTING
              data = data.
          CALL METHOD serializer->serialize( ).
          json = serializer->get_data( ).

2. 使用transformation进行json转换,如果需要字段映射保留大小写,可以自定义transformation

    DATA: lo_writer        TYPE REF TO cl_sxml_string_writer,
          lv_output_length TYPE i,
          lt_binary_tab    TYPE STANDARD TABLE OF sdokcntbin,
          lv_jsonx         TYPE xstring.

    FIELD-SYMBOLS:  TYPE i.

    ASSIGN ('IF_SXML=>CO_XT_JSON') TO .
    IF  IS ASSIGNED.

      lo_writer = cl_sxml_string_writer=>create( type =  ).

      CALL TRANSFORMATION id SOURCE text = data RESULT XML lo_writer.

      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   = rv_json
          output_length = lv_output_length
        TABLES
          binary_tab    = lt_binary_tab.

      " strip {"TEXT":
      rv_json = rv_json+8.

      " strip trailing }
      lv_output_length = strlen( rv_json ) - 1.
      rv_json = rv_json(lv_output_length).
    ENDIF.

3. git开源项目代码不再举例可自行关键词abap json搜索

你可能感兴趣的:(ABAP,速食,abap)