Manage NuGet ile Newtonsoft.Json dll indirin.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JsonDemo
{
public class Lesson
{
private static int lastId = 0;
public int Id { get; set; }
public string Name { get; set; }
public Lesson(string name)
{
Id = ++lastId;
Name = name;
}
}
class Student
{
private static int lastId = 0;
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthdate { get; set; }
public decimal Scholarship { get; set; }
public List Lessons { get; set; }
public Student()
{
Id = ++lastId;
Lessons = new List();
}
}
class Program
{
static void Main(string[] args)
{
var test = new Student()
{
Birthdate = new DateTime(2018, 7, 1),
Name = "Ad Soyad",
Scholarship = 100m,
Lessons = new List()
{
new Lesson("Math"),
new Lesson("Science")
}
};
//Serialize ile json string'e çevrilir.
//test nesnesini json'a string türüne çeviriyoruz.
//test: json formatına çevirilecek nesne
//Formatting.Indented: girintili olarak oluştur.
//Formatting.None: girintileri olmadan oluştur.
string jsonText = JsonConvert.SerializeObject(test, Formatting.Indented);
Console.WriteLine(jsonText);
//Deserialize ile tekrar nesneye çevrilir.
//Çevirilecek nesnenin türü olarak belirtilir.
Student student = JsonConvert.DeserializeObject<Student>(jsonText);
Console.WriteLine($"Id: {student.Id}, Name: {student.Name}, Birthdate: {student.Birthdate}, Schoolarship: {student.Scholarship}");
}
}
}