SlideShare a Scribd company logo
1 of 27
JSON MEETS NAV
WORKSHOP
GUNNAR GESTSSON
ADVANIA
Employee @ Advania (http://www.advania.is)
NAV technology, ISV, development and deployment
administration. AdvaniaGIT-SCM, Test, Build, Deploy
Community work @ Dynamics.is
Blog, workshops, sessions, collaboration
Software @ Objects4NAV (http://objects4nav.com)
Dynamics 365 and Appsource
Freelance work @ Navision.guru (http://navision.guru)
GIT, Data Exchange, Development, D365
Gunnar Gestsson has multiple hats
In computing, JavaScript Object Notation or JSON, is an open-standard file format
that uses human-readable text to transmit data objects consisting of attribute–
value pairs and array data types (or any other serializable value).
It is a very common data format used for asynchronous browser–server
communication, including as a replacement for XML in some AJAX-style systems.
JSON is a language-independent data format. It was derived from JavaScript, but as
of 2017 many programming languages include code to generate and parse JSON-
format data. The official Internet media type for JSON is application/json. JSON
filenames use the extension .json.
Json on Wikipedia 1
JSON's basic data types are:
• Number: a signed decimal number that may contain a fractional part and may use
exponential E notation, but cannot include non-numbers such as NaN. The format
makes no distinction between integer and floating-point. JavaScript uses a double-
precision floating-point format for all its numeric values, but other languages
implementing JSON may encode numbers differently.
• String: a sequence of zero or more Unicode characters. Strings are delimited with
double-quotation marks and support a backslash escaping syntax.
• Boolean: either of the values true or false
• Array: an ordered list of zero or more values, each of which may be of any type. Arrays
use square bracket notation and elements are comma-separated.
• Object: an unordered collection of name–value pairs where the names (also called keys)
keys) are strings. Since objects are intended to represent associative arrays, it is
recommended, though not required, that each key is unique within an object. Objects
are delimited with curly brackets and use commas to separate each pair, while within
each pair the colon ':' character separates the key or name from its value.
• null: An empty value, using the word null
Json on Wikipedia 2
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
…
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
Json Example
• Using the Customer table in the CRONUS
• Create Json Text for columns; No., Name,
Balance
• Read the actual table (non temporary)
• Write to a temporary table
• Combine Read and Write to verify the
results
Exercises
LOCAL PROCEDURE OpenJson@2(Json@1003 : Text);
VAR
TempBlob@1001 : Record 99008535;
FileMgt@1000 : Codeunit 419;
BEGIN
TempBlob.WriteAsText(Json,TEXTENCODING::UTF8);
FileMgt.BLOBExport(TempBlob,'OData.json',TRUE);
END;
See your results
• Json is just formatted text
• Make sure to escape special
characters
• b Backspace (ascii code 08)
• f Form feed (ascii code 0C)
• n New line
• r Carriage return
• t Tab
• " Double quote
•  Backslash character
LOCAL PROCEDURE EscValue@11(Value@1000 : Text) NewValue : Text;
VAR
Char@1001 : Char;
Pos@1002 : Integer;
BEGIN
IF Value = '' THEN EXIT('');
FOR Pos := 1 TO STRLEN(Value) DO BEGIN
Char := Value[Pos];
CASE Char OF
8: // Backspace
NewValue += 'b';
10: // New line
NewValue += 'n';
12: // Form feed
NewValue += 'f';
13: // Carriage return
NewValue += 'r';
9: // Tab
NewValue += 't';
34: // Double Quote
NewValue += '"';
92: // Backslash character
NewValue += '"';
ELSE
NewValue += COPYSTR(Value,Pos,1);
END;
END;
END;
Create Json manually?
• Start with a simple Json, for example a
copy of the Json from Wikipedia.
• Make sure the Json opens in the
correct program (I suggest Visual
Studio Code and I have Json Tools by
Erik Lynd installed in Visual Studio
Code as an extension).
• Create Json for the Customer Table
(No., Name, Balance)
• Make sure to have the correct
formatting of non-string values.
{ "Customer":
[
{
"No": "01121212",
"Name": "Spotsmeyer's Furnishings",
"Balance": "0.00"
},
{
"No": "01445544",
"Name": "Progressive Home Furnishings",
"Balance": "2310.38"
},
…
{
"No": "IC1030",
"Name": "Cronus Cardoxy Procurement",
"Balance": "0.00"
}
]
}
Exercise 1, Create Json manually
• Used in combination with StringBuilder and StringWriter to build
Json Text
• Json is created in a steam mode, not in object mode
• Will take care of string escape
• Codeunit 50001 on my USB
JsonTextWriter
• Use the Newtonsoft Wrapper Codeunit to create a Json with
Customer Data
• Results should be identical to the results in Exercise 1
• Try out the ShowJson function in Newtonsoft Wrapper Codeunit
to display the result in NAV. Try this codeunit as well for the
manually created Json.
Exercise 2, Create Json with JsonTextWriter
• Json Tokens
• Json Array
• Json Object
• Json Property
• Json Value
• JSON Management (Codeunit 5459)
• Object type build, not stream type build.
JObjects
• Create the same Customer Data Json as before, now using JSON Management
Codeunit.
• Repeat by using the Json DotNet objects without the JSON Management
Codeunit 5459
Exercise 3, Create Json with JObject
• Json can be converted to Xml
• Xml can be converted to Json
• Xml has a root element. Json does not need to.
• Converting from Json to Xml will always add a root element
• Converting from Xml to Json will always remove the root element
• [External] Functions will be in Codeunit 5459 in NAV 2018
• Use Codeunit 50002 from the USB
Json vs. Xml, convert to and from
[External]
PROCEDURE XMLTextToJSONText@29(Xml@1000 : Text) Json : Text;
VAR
XMLDOMMgt@1004 : Codeunit 6224;
JsonConvert@1003 : DotNet "'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'.Newtonsoft.Json.JsonConvert";
JsonFormatting@1002 : DotNet "'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'.Newtonsoft.Json.Formatting";
XmlDocument@1001 : DotNet "'System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlDocument";
BEGIN
XMLDOMMgt.LoadXMLDocumentFromText(Xml,XmlDocument);
Json := JsonConvert.SerializeXmlNode(XmlDocument.DocumentElement,JsonFormatting.Indented,TRUE);
END;
To convert an Xml to Json, use
[External]
PROCEDURE JSONTextToXMLText@34(Json@1001 :
Text;DocumentElementName@1000 : Text) Xml : Text;
VAR
JsonConvert@1004 : DotNet "'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'.Newtonsoft.Json.JsonConvert";
XmlDocument@1002 : DotNet "'System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlDocument";
BEGIN
XmlDocument := JsonConvert.DeserializeXmlNode(Json,DocumentElementName);
Xml := XmlDocument.OuterXml;
END;
To convert a Json to an Xml, use
{ "Customer":
[
{
"No": "01121212",
"Name": "Spotsmeyer's Furnishings",
"Balance": "0.00"
},
{
"No": "01445544",
"Name": "Progressive Home Furnishings",
"Balance": "2310.38"
},
…
{
"No": "IC1030",
"Name": "Cronus Cardoxy Procurement",
"Balance": "0.00"
}
]
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Json>
<Customer>
<No>01121212</No>
<Name>Spotsmeyer's Furnishings</Name>
<Balance>0.00</Balance>
</Customer>
<Customer>
<No>01445544</No>
<Name>Progressive Home Furnishings</Name>
<Balance>2310.38</Balance>
</Customer>
...
<Customer>
<No>IC1030</No>
<Name>Cronus Cardoxy Procurement</Name>
<Balance>0.00</Balance>
</Customer>
</Json>
Our Customer Json in Xml format
• We are familiar with the Xml layout
• We already know how to use Xml DOM
Codeunit 6224
• We have legacy code that created Xml from out
data
• We can use XmlPorts
Why converting between Json and Xml
Pros
• Limit the no. of code lines
• Will convert to AL and work in
Extension V2
• Combination of XmlPorts and
temporary table will map your data to
and from NAV structure fast and easy
Cons
• More NAV Objects
• Does not support Json value types
when writing Json since Xml only
supports Text values
Pros and Cons with XmlPorts
• Create a temporary table that will
match your Json
• Create an XmlPort to read/write that
temporary table
• Populate the temporary table from
the Customer Table to create the Xml
• Convert that Xml to Json, open and
compare to the previous exercises
• XmlPort uses Temporary Tables, add
[External]Get and [External]Set
functions to copy a temporary table
into and from the XmlPort
• XmlPort should use UFT-8
• XmlPort formatting should be Xml
• Remember a single Root Element
before adding the table data
• Use TempBlob.Blob to stream the data
in and out
Exercise 4, Create Json with XmlPort
• Manually – but I would not do that
• Convert Json to Xml and read with XmlPort and/or DOM
Codeunit 6224
• Use JsonTextReader to read Json to a buffer table (Json Buffer,
1236)
• Use JObject DotNet to read Json
Json readers
• Create a reader and try to read all of the four Json you
have already created.
• Try XmlPort reader, JsonTextReader and JObject DotNet
using the methods found in JSON Management Codeunit
5459
Exercise 5, Try different Json readers
• AL Comes with Json data types
• JsonObject
• JsonArray
• JsonToken
• JsonValue
• Based of the DotNet JObject we just used
• Simplified syntax
• Type conversion to native AL & C/AL data types
AL in Visual Studio Code
• Use the built in data types to create the customer Json in AL
• Also use the built in data types to read that customer Json back
into a temporary table and display to the user
Exercise 6, Create and read Json in AL
Add $format=json to the query
https://spla2016odata.navleiga.is/Kappi/OData/Company('Kappi%20ehf.')/InsightAc
countingPeriods?tenant=kappi&$format=json
Use
https://msdn.microsoft.com/en-us/library/dn182582(v=nav.90).aspx
http://www.kauffmann.nl/2015/11/26/web-services-examples-part-1-the-basic-
pattern/
Json in Odata services
Use the Web Service Access Key
Gunnar Gestsson
@ work, gunnar.gestsson@advania.is
@ community, gunnar@dynamics.is
@ freelance, gunnar@navision.guru
@ twitter, @gunnargestsson
@ linkedin, https://www.linkedin.com/in/gunnargestsson/
Enjoy our conference
Thanks for the day

More Related Content

What's hot

CSS3 2D/3D transform
CSS3 2D/3D transformCSS3 2D/3D transform
CSS3 2D/3D transform
Kenny Lee
 
Session 6 sv_randomization
Session 6 sv_randomizationSession 6 sv_randomization
Session 6 sv_randomization
Nirav Desai
 

What's hot (8)

Chapter04-web.pptx
Chapter04-web.pptxChapter04-web.pptx
Chapter04-web.pptx
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
CSS3 2D/3D transform
CSS3 2D/3D transformCSS3 2D/3D transform
CSS3 2D/3D transform
 
Css properties
Css propertiesCss properties
Css properties
 
CSS INHERITANCE
CSS INHERITANCECSS INHERITANCE
CSS INHERITANCE
 
Session 6 sv_randomization
Session 6 sv_randomizationSession 6 sv_randomization
Session 6 sv_randomization
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 
Building Netty Servers
Building Netty ServersBuilding Netty Servers
Building Netty Servers
 

Similar to NAVTechDays 2017 Json Meets NAV

json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
AmitSharma397241
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON Hackday
Somay Nakhal
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
titanlambda
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
HemaSenthil5
 

Similar to NAVTechDays 2017 Json Meets NAV (20)

JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
JSON Support in DB2 for z/OS
JSON Support in DB2 for z/OSJSON Support in DB2 for z/OS
JSON Support in DB2 for z/OS
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON Hackday
 
Json
JsonJson
Json
 
Native Phone Development 101
Native Phone Development 101Native Phone Development 101
Native Phone Development 101
 
Json
JsonJson
Json
 
JSON
JSONJSON
JSON
 
TypeScript and SharePoint Framework
TypeScript and SharePoint FrameworkTypeScript and SharePoint Framework
TypeScript and SharePoint Framework
 
Json
JsonJson
Json
 
Java script
Java scriptJava script
Java script
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
Going Native: Leveraging the New JSON Native Datatype in Oracle 21c
Going Native: Leveraging the New JSON Native Datatype in Oracle 21cGoing Native: Leveraging the New JSON Native Datatype in Oracle 21c
Going Native: Leveraging the New JSON Native Datatype in Oracle 21c
 
Web designing unit 4
Web designing unit 4Web designing unit 4
Web designing unit 4
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Json
JsonJson
Json
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 

NAVTechDays 2017 Json Meets NAV

  • 2. Employee @ Advania (http://www.advania.is) NAV technology, ISV, development and deployment administration. AdvaniaGIT-SCM, Test, Build, Deploy Community work @ Dynamics.is Blog, workshops, sessions, collaboration Software @ Objects4NAV (http://objects4nav.com) Dynamics 365 and Appsource Freelance work @ Navision.guru (http://navision.guru) GIT, Data Exchange, Development, D365 Gunnar Gestsson has multiple hats
  • 3. In computing, JavaScript Object Notation or JSON, is an open-standard file format that uses human-readable text to transmit data objects consisting of attribute– value pairs and array data types (or any other serializable value). It is a very common data format used for asynchronous browser–server communication, including as a replacement for XML in some AJAX-style systems. JSON is a language-independent data format. It was derived from JavaScript, but as of 2017 many programming languages include code to generate and parse JSON- format data. The official Internet media type for JSON is application/json. JSON filenames use the extension .json. Json on Wikipedia 1
  • 4. JSON's basic data types are: • Number: a signed decimal number that may contain a fractional part and may use exponential E notation, but cannot include non-numbers such as NaN. The format makes no distinction between integer and floating-point. JavaScript uses a double- precision floating-point format for all its numeric values, but other languages implementing JSON may encode numbers differently. • String: a sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax. • Boolean: either of the values true or false • Array: an ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation and elements are comma-separated. • Object: an unordered collection of name–value pairs where the names (also called keys) keys) are strings. Since objects are intended to represent associative arrays, it is recommended, though not required, that each key is unique within an object. Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value. • null: An empty value, using the word null Json on Wikipedia 2
  • 5. { "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, … { "type": "office", "number": "646 555-4567" }, { "type": "mobile", "number": "123 456-7890" } ], "children": [], "spouse": null } Json Example
  • 6. • Using the Customer table in the CRONUS • Create Json Text for columns; No., Name, Balance • Read the actual table (non temporary) • Write to a temporary table • Combine Read and Write to verify the results Exercises
  • 7. LOCAL PROCEDURE OpenJson@2(Json@1003 : Text); VAR TempBlob@1001 : Record 99008535; FileMgt@1000 : Codeunit 419; BEGIN TempBlob.WriteAsText(Json,TEXTENCODING::UTF8); FileMgt.BLOBExport(TempBlob,'OData.json',TRUE); END; See your results
  • 8. • Json is just formatted text • Make sure to escape special characters • b Backspace (ascii code 08) • f Form feed (ascii code 0C) • n New line • r Carriage return • t Tab • " Double quote • Backslash character LOCAL PROCEDURE EscValue@11(Value@1000 : Text) NewValue : Text; VAR Char@1001 : Char; Pos@1002 : Integer; BEGIN IF Value = '' THEN EXIT(''); FOR Pos := 1 TO STRLEN(Value) DO BEGIN Char := Value[Pos]; CASE Char OF 8: // Backspace NewValue += 'b'; 10: // New line NewValue += 'n'; 12: // Form feed NewValue += 'f'; 13: // Carriage return NewValue += 'r'; 9: // Tab NewValue += 't'; 34: // Double Quote NewValue += '"'; 92: // Backslash character NewValue += '"'; ELSE NewValue += COPYSTR(Value,Pos,1); END; END; END; Create Json manually?
  • 9. • Start with a simple Json, for example a copy of the Json from Wikipedia. • Make sure the Json opens in the correct program (I suggest Visual Studio Code and I have Json Tools by Erik Lynd installed in Visual Studio Code as an extension). • Create Json for the Customer Table (No., Name, Balance) • Make sure to have the correct formatting of non-string values. { "Customer": [ { "No": "01121212", "Name": "Spotsmeyer's Furnishings", "Balance": "0.00" }, { "No": "01445544", "Name": "Progressive Home Furnishings", "Balance": "2310.38" }, … { "No": "IC1030", "Name": "Cronus Cardoxy Procurement", "Balance": "0.00" } ] } Exercise 1, Create Json manually
  • 10. • Used in combination with StringBuilder and StringWriter to build Json Text • Json is created in a steam mode, not in object mode • Will take care of string escape • Codeunit 50001 on my USB JsonTextWriter
  • 11. • Use the Newtonsoft Wrapper Codeunit to create a Json with Customer Data • Results should be identical to the results in Exercise 1 • Try out the ShowJson function in Newtonsoft Wrapper Codeunit to display the result in NAV. Try this codeunit as well for the manually created Json. Exercise 2, Create Json with JsonTextWriter
  • 12. • Json Tokens • Json Array • Json Object • Json Property • Json Value • JSON Management (Codeunit 5459) • Object type build, not stream type build. JObjects
  • 13. • Create the same Customer Data Json as before, now using JSON Management Codeunit. • Repeat by using the Json DotNet objects without the JSON Management Codeunit 5459 Exercise 3, Create Json with JObject
  • 14. • Json can be converted to Xml • Xml can be converted to Json • Xml has a root element. Json does not need to. • Converting from Json to Xml will always add a root element • Converting from Xml to Json will always remove the root element • [External] Functions will be in Codeunit 5459 in NAV 2018 • Use Codeunit 50002 from the USB Json vs. Xml, convert to and from
  • 15. [External] PROCEDURE XMLTextToJSONText@29(Xml@1000 : Text) Json : Text; VAR XMLDOMMgt@1004 : Codeunit 6224; JsonConvert@1003 : DotNet "'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'.Newtonsoft.Json.JsonConvert"; JsonFormatting@1002 : DotNet "'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'.Newtonsoft.Json.Formatting"; XmlDocument@1001 : DotNet "'System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlDocument"; BEGIN XMLDOMMgt.LoadXMLDocumentFromText(Xml,XmlDocument); Json := JsonConvert.SerializeXmlNode(XmlDocument.DocumentElement,JsonFormatting.Indented,TRUE); END; To convert an Xml to Json, use
  • 16. [External] PROCEDURE JSONTextToXMLText@34(Json@1001 : Text;DocumentElementName@1000 : Text) Xml : Text; VAR JsonConvert@1004 : DotNet "'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'.Newtonsoft.Json.JsonConvert"; XmlDocument@1002 : DotNet "'System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlDocument"; BEGIN XmlDocument := JsonConvert.DeserializeXmlNode(Json,DocumentElementName); Xml := XmlDocument.OuterXml; END; To convert a Json to an Xml, use
  • 17. { "Customer": [ { "No": "01121212", "Name": "Spotsmeyer's Furnishings", "Balance": "0.00" }, { "No": "01445544", "Name": "Progressive Home Furnishings", "Balance": "2310.38" }, … { "No": "IC1030", "Name": "Cronus Cardoxy Procurement", "Balance": "0.00" } ] } <?xml version="1.0" encoding="UTF-8" standalone="no"?> <Json> <Customer> <No>01121212</No> <Name>Spotsmeyer's Furnishings</Name> <Balance>0.00</Balance> </Customer> <Customer> <No>01445544</No> <Name>Progressive Home Furnishings</Name> <Balance>2310.38</Balance> </Customer> ... <Customer> <No>IC1030</No> <Name>Cronus Cardoxy Procurement</Name> <Balance>0.00</Balance> </Customer> </Json> Our Customer Json in Xml format
  • 18. • We are familiar with the Xml layout • We already know how to use Xml DOM Codeunit 6224 • We have legacy code that created Xml from out data • We can use XmlPorts Why converting between Json and Xml
  • 19. Pros • Limit the no. of code lines • Will convert to AL and work in Extension V2 • Combination of XmlPorts and temporary table will map your data to and from NAV structure fast and easy Cons • More NAV Objects • Does not support Json value types when writing Json since Xml only supports Text values Pros and Cons with XmlPorts
  • 20. • Create a temporary table that will match your Json • Create an XmlPort to read/write that temporary table • Populate the temporary table from the Customer Table to create the Xml • Convert that Xml to Json, open and compare to the previous exercises • XmlPort uses Temporary Tables, add [External]Get and [External]Set functions to copy a temporary table into and from the XmlPort • XmlPort should use UFT-8 • XmlPort formatting should be Xml • Remember a single Root Element before adding the table data • Use TempBlob.Blob to stream the data in and out Exercise 4, Create Json with XmlPort
  • 21. • Manually – but I would not do that • Convert Json to Xml and read with XmlPort and/or DOM Codeunit 6224 • Use JsonTextReader to read Json to a buffer table (Json Buffer, 1236) • Use JObject DotNet to read Json Json readers
  • 22. • Create a reader and try to read all of the four Json you have already created. • Try XmlPort reader, JsonTextReader and JObject DotNet using the methods found in JSON Management Codeunit 5459 Exercise 5, Try different Json readers
  • 23. • AL Comes with Json data types • JsonObject • JsonArray • JsonToken • JsonValue • Based of the DotNet JObject we just used • Simplified syntax • Type conversion to native AL & C/AL data types AL in Visual Studio Code
  • 24. • Use the built in data types to create the customer Json in AL • Also use the built in data types to read that customer Json back into a temporary table and display to the user Exercise 6, Create and read Json in AL
  • 25. Add $format=json to the query https://spla2016odata.navleiga.is/Kappi/OData/Company('Kappi%20ehf.')/InsightAc countingPeriods?tenant=kappi&$format=json Use https://msdn.microsoft.com/en-us/library/dn182582(v=nav.90).aspx http://www.kauffmann.nl/2015/11/26/web-services-examples-part-1-the-basic- pattern/ Json in Odata services
  • 26. Use the Web Service Access Key
  • 27. Gunnar Gestsson @ work, gunnar.gestsson@advania.is @ community, gunnar@dynamics.is @ freelance, gunnar@navision.guru @ twitter, @gunnargestsson @ linkedin, https://www.linkedin.com/in/gunnargestsson/ Enjoy our conference Thanks for the day