C#’ta JSON Nedir ve Nasıl Kullanılır

Bu yazı ilk olarak Nisan 2016’da C# Corner’da yayımlanmıştır (~2,9k okunma). Kendi siteme yeniden eklenmiştir.

Bu yazıda JSON’ın ne olduğunu, C#’ta nasıl JSON string oluşturulacağını ve bir JSON string’in nasıl okunacağını anlatıyorum.

JSON Nedir

JSON (JavaScript Object Notation), insan tarafından okunabilir veri alışverişi için tasarlanmış bir standarttır. Ağaç yapısıyla çalışır ve XML’e benzer; ama daha kısa ve kullanımı daha kolaydır. XML deneyiminiz varsa hızlıca öğrenirsiniz.

JSON, { "key": "value" } mantığını izler ve dizileri de destekler. Köşeli parantez [ ] bir değerler dizisini ifade eder.

C#’ta JSON string nasıl oluşturulur

Visual Studio’da yeni bir Console Application oluşturun, ardından Newtonsoft.Json NuGet paketini kurup using Newtonsoft.Json; ekleyin. Örnek JSON:

{
    "universities": {
        "university": "South Carolina State University",
        "students": [
            { "name": "Stephen Cousins" },
            { "name": "Austin A. Newton" },
            { "name": "Adam Wilhite" },
            { "name": "Enis Kurtay YILMAZ" }
        ]
    }
}

C#’ta JSON string oluşturma:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace EKY.CSharpCornerJSONArticle
{
    public class Student
    {
        public string name { get; set; }
    }

    public class Universities
    {
        public string university { get; set; }
        public IList<Student> students { get; set; }
    }

    public class ClassUniversities
    {
        public Universities universities { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ClassUniversities university1 = new ClassUniversities();

            university1.universities = new Universities();
            university1.universities.university = "South Carolina State University";

            List<Student> listStudent = new List<Student>();
            Student student1 = new Student { name = "Stephen Cousins" };
            Student student2 = new Student { name = "Austin A. Newton" };
            Student student3 = new Student { name = "Adam Wilhite" };
            Student student4 = new Student { name = "Enis Kurtay YILMAZ" };

            listStudent.Add(student1);
            listStudent.Add(student2);
            listStudent.Add(student3);
            listStudent.Add(student4);

            university1.universities.students = listStudent;
            string json = JsonConvert.SerializeObject(university1);

            Console.WriteLine(json);
            Console.ReadLine();
        }
    }
}

C#’ta JSON string nasıl okunur

Deserialize etmek için yalnızca örnek bir JSON string’e ve eşleşen C# sınıflarına ihtiyacınız var. Bir URL’den JSON okuma örneği:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net;
using System.IO;

namespace EKY.CSharpCornerJSONArticle
{
    public class Post
    {
        public int id { get; set; }
        public string slug { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public string date { get; set; }
    }

    public class ClassWebsiteposts
    {
        public string status { get; set; }
        public int count { get; set; }
        public IList<Post> posts { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string url = "https://www.eniskurtayyilmaz.com/api/get_posts/";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            string jsonValue = "";
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                jsonValue = reader.ReadToEnd();
            }

            ClassWebsiteposts websitePosts = JsonConvert.DeserializeObject<ClassWebsiteposts>(jsonValue);
        }
    }
}