1、JSON数组
报文格式如下,是JSON 数组类型的。
[
{
"I_TYPE":"V",
"I_BUSINESSSCOPE":"1001"
},
{
"I_TYPE":"V",
"I_BUSINESSSCOPE":"1002"
}
]
json转换为SAP内表:
TYPES: BEGIN OF ty_in1,
I_TYPE(1),
I_BUSINESSSCOPE(10),
END OF ty_in1.
DATA: gt_in1 TYPE TABLE OF ty_in1,
gs_in1 TYPE ty_in1.
CALL METHOD /ui2/cl_json=>deserialize
EXPORTING
json = i_json "i_json是输入的json字符串
CHANGING
data = gt_in1[].
解析结果:
2、JSON对象+JSON数组
报文格式如下,是有头和行项目的JSON报文
{
"IHEADER":{
"I_BKTXT":"测试1",
"I_USNAM":"J007"
},
"ITEM":[
{
"I_TYPE":"V",
"I_BUSINESSSCOPE":"1021"
}
]
}
sap结构定义如下,需注意头IHEADER和ITEM报文中需和定义的保持一致,
DATA:BEGIN OF ty_header,
I_BKTXT(30),
I_USNAM(10),
END OF ty_header,
BEGIN OF ty_item,
i_type(1),
i_businessscope(10),
END OF ty_item,
BEGIN OF ty_in2,
iheader LIKE ty_header,
itable LIKE TABLE OF ty_item,
END OF ty_in2.
DATA: is_header LIKE ty_header,
it_item LIKE TABLE OF ty_item.
*JSON->内表
CALL METHOD /ui2/cl_json=>deserialize
EXPORTING
json = i_json "jsonstr是json字符串
CHANGING
data = ty_in2.
*另一种方式,同上
/ui2/cl_json=>deserialize(
EXPORTING json = i_json
CHANGING data = ty_in2 ).
is_header = ty_in2-iheader.
it_item = ty_in2-item.
解析结果:
注意:/ui2/cl_json通常都可以解析,需要特别留意的是CHANGING参数的结构的定义,如果定义不一致,可能解析不出来。
3、内表转JSON
CALL METHOD /ui2/cl_json=>serialize
EXPORTING
data = gt_out
RECEIVING
r_json = O_JSON.
输出JSON:
[
{
"EBELN":"4500000107",
"BEDAT":"2016-03-03"
},
{
"EBELN":"4500000109",
"BEDAT":"2016-03-03"
},
{
"EBELN":"4500000119",
"BEDAT":"2016-03-03"
}
]
下发单条信息:
LOOP AT it_ekko INTO wa_ekko.
o_json = /ui2/cl_json=>serialize( data = wa_ekko ).
ENDLOOP.
o_json = /ui2/cl_json=>serialize( data = wa_ekko compress = abap_true pretty_name = abap_true ).
compress = abap_true pretty_name = abap_true 可以将字段大写转小写。
三条独立的报文:
{"EBELN":"4500000107","BEDAT":"2016-03-03"}
{"EBELN":"4500000109","BEDAT":"2016-03-03"}
{"EBELN":"4500000119","BEDAT":"2016-03-03"}
参考文档:
SAP之JSON转换 - 知乎
ABAP: 定义结构_abap types 包含表结构_阿达hi的博客-CSDN博客
ABAP 接口开发之HTTP传输JSON的封装和解析_HeathlX的博客-CSDN博客
JSON和SAP内表转化_/ui2/cl_json=>deserialize-CSDN博客
JSON格式报文介绍参考:
JSON入门看这一篇就够了 - 知乎
json的几种标准格式_json格式-CSDN博客