Because I needed it today for simulating a response of a web service in a unit test and couldn’t find a suitable example over the internet, let’s see how we can create a Simple Json file in NAV C/AL.
Sample test codeunit:
OnRun() CreateSimpleJsonFile(JSonResponse); MESSAGE('id: %1 ; status: %2', FORMAT(JSonResponse.GetValue('id')), FORMAT(JSonResponse.GetValue('status'))); JsonString := JSonResponse.ToString(); MyFile.CREATE('C:\Temp\JsonTest.txt'); MyFile.CREATEOUTSTREAM(OutStr); OutStr.WRITETEXT(JsonString); LOCAL CreateSimpleJsonFile(VAR JSonResponse : DotNet "Newtonsoft.Json.Linq.JObject") JSonResponse := JSonResponse.JObject(); JsonTextWriter := JSonResponse.CreateWriter(); JsonTextWriter.WritePropertyName('id'); JsonTextWriter.WriteValue(LibraryRandom.RandInt(50000)); JsonTextWriter.WritePropertyName('status'); JsonTextWriter.WriteValue('done');
Variables function Create SimpleJsonFile:
Var Name DataType Subtype Length
Yes JSonResponse DotNet Newtonsoft.Json.Linq.JObject.’Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed’
Name DataType Subtype Length
JsonTextWriter DotNet Newtonsoft.Json.JsonTextWriter.’Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed’
LibraryRandom Codeunit Library – Random
Variables OnRun trigger:
Name DataType Subtype Length
JSonResponse DotNet Newtonsoft.Json.Linq.JObject.’Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed’
JsonString Text
MyFile File
OutStr OutStream
For this example you need to install the NewtonSoft Json dll in your Add-ins folder. See also this post.
After running the sample codeunit you get a message with the values from the generated Json file:
And in C:/Temp you can see the JsonTest.txt file:
{
“id”: 29562,
“status”: “done”
}
In NAV AL (VS Code) will be easier to work with Json files. For this, we will use the Json API Microsoft provided in order to work with Json without DotNet interoperability. Example:
You can find the Sample file in my newly created Git “Utilities” repository:
https://github.com/andreilungu/Utilities
how do we read the json file and parse the data into the table in Navision 2018
Hi, you can do this in multiple ways. Examples:
https://dynamics.is/?p=2303
https://dynamics.is/?p=2637
https://andreilungu.com/web-service-and-xml-in-nav/
https://andreilungu.com/use-rest-web-service-import-to-business-central/