JSON Object into a Dictionary Data Type - Business Central

 The Dictionary Data Type represents an unordered collection of keys and values and is optimized for fast lookup of values. Each addition to the dictionary consists of a value and its associated key. Every key in a Dictionary must be unique. It is on my list of favorite “new” AL Data Types, and I find it often easier to work with a dictionary than another object type.

In this example, a JSON Object’s value keys (not the array or object keys) are copied into a Dictionary Data Type variable.

procedure JsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text]) var IsHandled: Boolean; JsonToken: JsonToken; DuplicateKeyErr: label 'Duplicate Key %1', Comment = '%1 Key Name'; ObjectKeys: List of [Text]; JKey: Text; JValue: Text; begin Clear(ObjectDictionary); OnBeforeJsonObjectValuestoDictionary(JObject, ObjectDictionary, IsHandled); if IsHandled then exit; ObjectKeys := JObject.Keys(); foreach JKey in ObjectKeys do begin JObject.Get(Jkey, JsonToken); if JsonToken.IsValue then begin if ObjectDictionary.ContainsKey(JKey) then Error(DuplicateKeyErr, JKey); JsonToken.WriteTo(JValue); ObjectDictionary.Add(DelChr(JKey, '=', '"'), DelChr(JValue, '=', '"')); end; end; OnAfterJsonObjectValuestoDictionary(JObject, ObjectDictionary); end; [BusinessEvent(false)] local procedure OnAfterJsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text]) begin end; [BusinessEvent(false)] local procedure OnBeforeJsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text]; var Handled: Boolean) begin end;

No comments:

Post a Comment