[JavaScript] String in JSON wandeln

Beispiel 1 (simpel)

// https://javascript.info/json

// JSON-Objekt definieren
let sJSON = '{ "name":"Heinz","age":"56","city":"Hamburg" }';

// JSON-Objekt aus String parsen
let oJSONpar = JSON.parse(sJSON);

// Testausgabe
console.log(oJSONpar.name);

Beispiel 2 (reviver)

// JSON-Objekt definieren
let sJSON = '{ "name":"Heinz","age":"56","city":"Hamburg","birth":"2018-04-25T12:00:00.000Z" }';

// JSON-Objekt aus String parsen
let oJSONpar = JSON.parse(sJSON, function(key, value) {

  // wenn Datumsfeld "birth"
  if (key == 'birth')
  {
      // Datumsobjekt zurückgeben
      return new Date(value);
  }
  else
  {
      return value;
  };
});

// Geburtsdatum ist jetzt vom Typ "Date" mit enspr. Funktionen
console.log(oJSONpar.birth.toLocaleString('de-DE'));

[JavaScript] JSON-Datei per HTTP-Request holen und parsen

// Link zur JSON-Datei
let sURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
// Request-Object
let request = new XMLHttpRequest();
// MIME-Typen
// txt: "text/plain"
// html: "text/html"
// json: "application/json"
request.overrideMimeType('application/json');
// Requestmethode
request.open('GET', sURL, true);
// Datentyp
request.responseType = 'text';
// Handler für asyncrone Antwort des Requests
// wenn Daten erfolgreich geladen
request.onload = function() {
  console.log('onload()');
  // gesamte Response ausgeben
  let sJSON = request.response;
  console.log(sJSON);
  
  // JSON-Daten parsen
  let oJSON = JSON.parse(sJSON);
  // Wert eines Attributes ausgeben
  console.log(oJSON.homeTown);
};
// bei Änderung des Ready-States
request.onreadystatechange = function () {
  console.log('onreadystatechange()');
  console.log(request.readyState);
  console.log(request.status);
  console.log(request.statusText);
};
// Request absenden
request.send();

[ABAP] XML nach JSON parsen

* XML-Daten
DATA(lv_xml) = |<object-><str name="text"->abcd</str-><bool name="flag"->true</bool-><member name="number"-><num->111</num-></member-><member name="content"-><null /-></member-></object->|.

TRY.
* XML-Daten lesen
    DATA(o_r) = cl_sxml_string_reader=>create( input = cl_abap_codepage=>convert_to( lv_xml ) ).
* evtl. Objektkomponenten mit <member->-Elementen darstellen
*    reader->set_option( if_sxml_reader=>co_opt_sep_member ).

    DATA(o_w) = CAST if_sxml_writer( cl_sxml_string_writer=>create( type     = if_sxml=>co_xt_json
                                                                    encoding = 'UTF-8' ) ).
* Ausgabeoptionen setzen
    o_w->set_option( option = if_sxml_writer=>co_opt_linebreaks ).
    o_w->set_option( option = if_sxml_writer=>co_opt_indent ).

    o_r->next_node( ).
* JSON parsen
    o_r->skip_node( o_w ).

* Ausgabe konvertieren
    DATA(lv_json) = cl_abap_codepage=>convert_from( CAST cl_sxml_string_writer( o_w )->get_output( ) ).

* JSON ausgeben
    cl_demo_output=>display_json( lv_json ).
  CATCH cx_root INTO DATA(e_txt).
    WRITE: / e_txt->get_text( ).
ENDTRY.

[ABAP] ABAPJSON Serializer / Deserializer

SELECT * FROM sflight INTO TABLE @DATA(it_flight).

* ABAP->JSON
DATA(lv_json) = /ui2/cl_json=>serialize( data = it_flight
                                         compress = abap_true
                                         pretty_name = /ui2/cl_json=>pretty_mode-camel_case ).

WRITE: / lv_json.

DATA: it_flight_json TYPE STANDARD TABLE OF sflight WITH DEFAULT KEY.

* JSON->ABAP
/ui2/cl_json=>deserialize( EXPORTING
                             json = lv_json
                             pretty_name = /ui2/cl_json=>pretty_mode-camel_case
                           CHANGING
                             data = it_flight_json ).

* ABAP object ->JSON
DATA(o_descr) = cl_abap_typedescr=>describe_by_data( it_flight_json ).
DATA(lv_json2) = /ui2/cl_json=>serialize( o_descr ).

WRITE: / lv_json2.

Weiterführende Infos: Link

[ABAP] Konvertierung string JSON XML, iTab JSON

TYPES: BEGIN OF s_person,
         name  TYPE string,
         title TYPE string,
         age   TYPE i,
       END OF s_person.

TYPES: t_person TYPE STANDARD TABLE OF s_person WITH DEFAULT KEY.

DATA: text TYPE string VALUE 'Hello JSON, here is ABAP!'.

* ABAP (string) -> JSON
DATA(o_writer_json) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
CALL TRANSFORMATION id SOURCE text = text RESULT XML o_writer_json.
DATA(json) = cl_abap_codepage=>convert_from( o_writer_json->get_output( ) ).

WRITE: / 'ABAP (string) )-> JSON: ', json.

* ABAP (string) -> JSON-XML
DATA(o_writer_xml) = cl_sxml_string_writer=>create( if_sxml=>co_xt_xml10 ).
CALL TRANSFORMATION id SOURCE text = text RESULT XML o_writer_xml.
DATA(xml) = cl_abap_codepage=>convert_from( o_writer_xml->get_output( ) ).

WRITE: / 'ABAP (string) -> JSON-XML: ', xml.

* JSON-XML -> ABAP (string)
CALL TRANSFORMATION id SOURCE XML json RESULT text = text.

WRITE: / 'JSON-XML -> ABAP (string): ', text.

* iTab
DATA(it_persons) = VALUE t_person( ( name = 'Horst' title = 'Herr' age = 30 )
                                   ( name = 'Jutta' title = 'Frau' age = 35 )
                                   ( name = 'Ingo' title = 'Herr' age = 31 ) ).

* ABAP (iTab) -> XML
DATA(o_writer_itab_xml) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_xml10 ).
CALL TRANSFORMATION id SOURCE values = it_persons RESULT XML o_writer_itab_xml.
DATA(itab_xml) = cl_abap_codepage=>convert_from( o_writer_itab_xml->get_output( ) ).

WRITE: / 'ABAP (iTab) -> XML: ', itab_xml.

* XML -> ABAP (itab)
CLEAR it_persons.
CALL TRANSFORMATION id SOURCE XML itab_xml RESULT values = it_persons.

IF lines( it_persons ) > 0.
  WRITE: / 'XML -> ABAP (itab): ', it_persons[ 1 ]-name.
ENDIF.

* ABAP (iTab) -> JSON
DATA(o_writer_itab) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
CALL TRANSFORMATION id SOURCE values = it_persons RESULT XML o_writer_itab.
DATA: lv_result TYPE string.
cl_abap_conv_in_ce=>create( )->convert( EXPORTING
                                          input = o_writer_itab->get_output( )
                                        IMPORTING
                                          data = lv_result ).

WRITE: / 'ABAP (iTab) -> JSON: ', lv_result.

* JSON -> ABAP (iTab)
CLEAR it_persons.
CALL TRANSFORMATION id SOURCE XML lv_result RESULT values = it_persons.

IF lines( it_persons ) > 0.
  WRITE: / 'JSON -> ABAP (iTab): ', it_persons[ 1 ]-name.
ENDIF.

* ABAP (iTab) -> JSON (trex)
DATA(o_trex) = NEW cl_trex_json_serializer( it_persons ).
o_trex->serialize( ).
DATA(lv_trex_json) = o_trex->get_data( ).

WRITE: / 'ABAP (iTab) -> JSON (trex): ', lv_trex_json.

[C#] JSON serialisieren/deserialisieren

JSON-Daten liegen in einem eigenen Format vor. Um dieses Datenformat in C# abzubilden benötigt man zuerst eine oder mehrere Klassen. Der Einfachheit halber kann man sich auf der Seite http://json2csharp.com/ aus dem JSON-Datenformat automatisiert C#-Klassen bauen lassen.

Als Beispiel dient folgende JSON-Datei:

{
"SerialNumber": "05857628",
"DateTime": "1415783932",
"Meters": [{
"InputNumber": "1",
"Name": "HZ Wirkleistung BZ 90612021",
"Type": "Electricity",
"Value": 2092224.000,
"Unit": "Wirkleistung"
},
{
"InputNumber": "2",
"Name": "HZ Blindleistung BZ 90612021",
"Type": "Electricity",
"Value": 2093763.500,
"Unit": "Blindleistung"
},
]
}

Die zugehörigen C#-Klassen sehen wie folgt aus:

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace JSONTest
{
    [DataContract]
    public class Meter
    {
        [DataMember]
        public string InputNumber { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Type { get; set; }
        [DataMember]
        public double? Value { get; set; }
        [DataMember]
        public string Unit { get; set; }
    }

    [DataContract]
    public class Meter_List
    {
        [DataMember]
        public string SerialNumber { get; set; }
        [DataMember]
        public string DateTime { get; set; }
        [DataMember]
        public List<Meter-> Meters { get; set; }
    }
}

Im Code greift man nun folgendermaßen auf die Daten zu:

// im Projektbaum Verweis hinzufügen: System.Runtime.Serialization
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

private void btnGetJSON_Click(object sender, EventArgs e)
{
	// JSON-File von URL holen
	string contents = new System.Net.WebClient().DownloadString("www.datenquelle.de");

	// JSON deserialisieren
	DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Meter_List));
	MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(contents));
	Meter_List obj = (Meter_List)ser.ReadObject(stream);

	// Daten ausgeben
	Console.WriteLine(obj.SerialNumber);
	Console.WriteLine(obj.Meters.Count);
	Console.WriteLine(obj.Meters[0].Name);
}

Quelle: Serializing and Deserializing JSON in C#