sbcgua / ajson

Yet another json parser serializer for ABAP
MIT License
50 stars 15 forks source link

Q: Guidance for replacing `create_empty` #144

Closed albertmink closed 1 year ago

albertmink commented 1 year ago

In abapGit we have

lo_mapping = zcl_abapgit_ajson_mapping=>create_camel_case( iv_first_json_upper = abap_false ).

lo_ajson = zcl_abapgit_ajson=>create_empty( ii_custom_mapping = lo_mapping ).

lo_ajson->keep_item_order( ).
lo_ajson->set(
  iv_path = '/'
  iv_val  = iv_data ).

see, https://github.com/abapGit/abapGit/blob/95389c532bb01dac7ff67ad374ec4cdbd54e78cb/src/objects/aff/zcl_abapgit_json_handler.clas.abap#L249-L256

According to the readme page (Deprecation notes), the create_empty might be deprecated and new is the new one. Now, I put those lines together and came up with this one

lo_ajson_2 = zcl_abapgit_ajson=>new( iv_keep_item_order = abap_true
  )->map( zcl_abapgit_ajson_mapping=>create_to_snake_case( )
    )->set( iv_path = '/'
            iv_val  = iv_data ).

When stringify the latter object, the data is not rendered as snakeCase, see

Screenshot 2023-01-11 at 15 43 28

Any advise?

sbcgua commented 1 year ago

Did you mean camelCase instead of snake_case ?

But yes, the concept of mapping has changed kind of the opposite it was before. Before the mapper was used directly for each set, it was kind passive ability of a given ajson instance. Now it is an active transformation of an existing and complete json. So in your example set and map should be swapped. as well as create_camel_case should be used. Snake cases is the one with_underscores, so abap like. The camelCase is JS like.

report ztest152.

types:
  begin of ty_1,
    format_version type string,
    begin of header,
      desc type string,
      orig_lang type c length 1,
      abap_lang_ver type string,
    end of header,
    cat type string,
  end of ty_1.

data lv_dummy type ty_1.

lv_dummy-format_version = '1'.
lv_dummy-cat = '123'.
lv_dummy-header-desc = 'hello'.
lv_dummy-header-orig_lang = 'E'.
lv_dummy-header-abap_lang_ver = '740'.

data lo_ajson type ref to zif_ajson.
lo_ajson = zcl_ajson=>new( iv_keep_item_order = abap_true
  )->set(
    iv_path = '/'
    iv_val  = lv_dummy
  )->map( zcl_ajson_mapping=>create_to_camel_case( ) ). " <<< mapper is applied to a complete and final json to create a new transformed one

cl_demo_output=>display( lo_ajson->stringify( ) ).

image

P.S. from readability perspective I'd also separate creation and transformation. But it's just my opinion.

lo_ajson = zcl_ajson=>new( iv_keep_item_order = abap_true
  )->set(
    iv_path = '/'
    iv_val  = lv_dummy
  )->set( ...

...

cl_demo_output=>display( lo_ajson->map( ... )->stringify( ) ).
albertmink commented 1 year ago

Thanks a lot. It works now.