Skip to content

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

1
2
3
4
5
6
7
8
{
    "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

1
2
3
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
1
2
3
4
5
class WeatherForecast {    
    public DateTime Date { get; set; }    
    public double TempC { get; set; }    
    public string Summary { get; set; }
}

Serialization

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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));
1
2
3
4
5
{
  "Date": "2020-10-08T23:06:54.197136+03:00",
  "TempC": 31.45,
  "Summary": "Very hot!"
}

Deserialization

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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

1
2
3
using (StreamWriter writer = System.IO.File.AppendText("logfile.txt")) {
    writer.WriteLine("log message"); 
}