03 - JSON
JSON - JavaScript Object Notation
Final standard.
DataTypes:
- String
- Number
- Object – {….}
- Array (one dimensional only. Jagged is ok) – [….]
- True
- False
- Null
Example of JSON
{
"FirstName": "Andres",
"LastName": "Käver",
"Subjects": ["C#", "Android"]
}
Serialization & Deserialization
Serialization - Converting objects to bytestream
Deserialization - Converting bytestream to objects
JSON in .NET since .NET Core 3
New serialization library
!!! warning Does not support multidimensional arrays
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
class WeatherForecast {
public DateTime Date { get; set; }
public double TempC { get; set; }
public string Summary { get; set; }
}
Serialization
var jsonOptions = new JsonSerializerOptions()
{
WriteIndented = true,
AllowTrailingCommas = true,
};
var w = new WeatherForecast()
{
Date = DateTime.Now,
TempC = 31.45,
Summary = "Very hot!"
};
Console.WriteLine(JsonSerializer.Serialize(w, jsonOptions));
{
"Date": "2020-10-08T23:06:54.197136+03:00",
"TempC": 31.45,
"Summary": "Very hot!"
}
Deserialization
var jsonOptions = new JsonSerializerOptions()
{
WriteIndented = true,
AllowTrailingCommas = true,
};
var jsonStr = @"
{
""Date"": ""2020-10-08T23:06:54.197136+03:00"",
""TempC"": 31.45,
""Summary"": ""Very hot!""
}";
var ww = JsonSerializer.Deserialize<WeatherForecast>(jsonStr, jsonOptions);
Console.WriteLine(ww.Date);
Console.WriteLine(ww.TempC);
Console.WriteLine(ww.Summary);
Newtonsoft library
If you need/want to use json with multidimensional arrays – Newtonsoft library supports it.
Newtonsoft is very mature, slightly slower 3rd party library.
Newtonsoft is not allowed in this course (or next). Stick to the standards!
Circular reference serialization is also forbidden!
FIle IO
System.IO.File namespace
AppendText
CreateText
using (StreamWriter writer = System.IO.File.AppendText("logfile.txt")) {
writer.WriteLine("log message");
}