JSON和SAP内表转化

Json格式与SAP内表转化

  • 一、json转内表(/ui2/cl_json=>deserialize)
    • 1、josn格式,key 和value是带双引号
    • 2、定义和josn格式相同的内表
    • 3、调用SAP内部函数
  • 二、内表结构转json
    • 1、定义结构
    • 2、内表转Json

一、json转内表(/ui2/cl_json=>deserialize)

1、josn格式,key 和value是带双引号

josn格式,key 和value是带双引号的,使用 /ui2/cl_json=>deserialize反序列化
如下面的json格式

[
   {
    "Z002S": "6-QTF-60 蓝色AC款纸箱 B17815T\n",
    "SQDH": "SD-031457",
    "POSNR": "10",
    "Z007S": "特殊商标 - ZNG-SB18815T\n",
    "MATNR": "VC-6-QTF-60"
  },
 {
  "Z002S": "6-QTF-70 蓝色AC款包装B17816T\n",
  "SQDH": "SD-031457",
  "POSNR": "20",
  "Z007S": "特殊商标 - ZNG-SB18816T\n",
  "MATNR": "VC-6-QTF-70"
 }
]

2、定义和josn格式相同的内表

定义内表

DATA: BEGIN OF it_itab OCCURS 0,
           SQDH(200)   TYPE c,
           MATNR(36)   TYPE c,
           POSNR(2)    TYPE c,
           Z002S(255)  TYPE c,
           Z007S(255)  TYPE c,
         END OF it_itab.

3、调用SAP内部函数

"JSON->内表 
   CALL METHOD /ui2/cl_json=>deserialize
        EXPORTING
           json = jsonstr                             "jsonstr是json字符串
         CHANGING
            data = it_itab[].                         “it_itab[]是转化的内表,中括号一定要有

二、内表结构转json

1、定义结构

  TYPES: BEGIN OF ZSEND_SMS_DATA,
           phonenumber(255)            TYPE c,
           templateparamcode(200)      TYPE c,
           type(200)                   TYPE c,
           notifytype(200)             TYPE c,
         END OF ZSEND_SMS_DATA.

data:ls_ZSEND_SMS_DATA TYPE ZSEND_SMS_DATA. 

DATA: lv_json_str TYPE string.  “要转化的json

2、内表转Json

“内表结构

ls_ZSEND_SMS_DATA-phonenumber = '13403124706'.

ls_ZSEND_SMS_DATA-templateparamcode = '1'.

ls_ZSEND_SMS_DATA-type = '1'.

ls_ZSEND_SMS_DATA-notifytype = '13403124706'.


"内表转josn

lv_json_str = /ui2/cl_json=>serialize( data = ls_ZSEND_SMS_DATA compress = abap_true pretty_name = abap_true ).

注意:需要对一些特殊字符做处理,否则外部系统处理JSON数据时会报错

REPLACE '&' WITH '' INTOlv_json_str.
REPLACE '\R' WITH '' INTO lv_json_str.
REPLACE '\N' WITH '' INTO lv_json_str.
REPLACE ALLOCCURRENCES OF '\' in lv_json_str with '/'.
REPLACE ALL OCCURRENCES of '"' in lv_json_str with ''.

最后转化的json格式:
{       
    "PhoneNumbers": "13403124706",
     "TemplateParamCode": null,
     "Type": "1",
     "NotifyType": "11"
   }

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