การใช้งาน Newtonsoft.Json เบื้องต้น

  1. ติดตั้ง Newtonsoft สำหรับ Json บน VS 2013
  2. ติดตั้ง Newtonsoft.Json บน VS 2017
  3. การแปลง JSON เป็นคลาส และคลาสเป็น JSON

1.ติดตั้ง Newtonsoft สำหรับ Json บน VS 2013

ใช้ NuGet ติดตั้ง Json.NET บน Visual Studio 2013 แล้ว Error ตามนี้

'Newtonsoft.Json' already has a dependency defined for 'Microsoft.CSharp'

ลองติดตั้งผ่าน console ของ PM ด้วยเวอร์ขันเก่า (9.0.1)

PM> Install-Package Newtonsoft.Json -Version 9.0.1
Installing 'Newtonsoft.Json 9.0.1'.
Successfully installed 'Newtonsoft.Json 9.0.1'.
Adding 'Newtonsoft.Json 9.0.1' to JackWebServices.
Successfully added 'Newtonsoft.Json 9.0.1' to JackWebServices.

ใช้ได้ แต่ถ้าจะไม่ระบุเวอร์ชันก็ตัด option -Version ออก

สร้างคลาสของข้อมูลที่จะส่ง

public class Result
{
    public int id { get; set; }
    public string value { get; set; }
    public string info { get; set; }
}

การใช้งานก็ใช้คำสั่ง JsonConvert.SerializeObject()

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

ผลลัพธ์

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"JKL","info":"JKL"}]}

Link

2.ติดตั้ง Newtonsoft.Json บน VS 2017

ติดตั้ง Newtonsoft.Json.11.0.2 บน Visual Studio 2017

PM> Install-Package Newtonsoft.Json

Attempting to gather dependency information for package 'Newtonsoft.Json.11.0.2' with respect to project 'ConsoleApp1', targeting '.NETFramework,Version=v4.6.1'
Gathering dependency information took 20.47 ms
Attempting to resolve dependencies for package 'Newtonsoft.Json.11.0.2' with DependencyBehavior 'Lowest'
Resolving dependency information took 0 ms
Resolving actions to install package 'Newtonsoft.Json.11.0.2'
Resolved actions to install package 'Newtonsoft.Json.11.0.2'
Retrieving package 'Newtonsoft.Json 11.0.2' from 'nuget.org'.
  GET https://api.nuget.org/v3-flatcontainer/newtonsoft.json/11.0.2/newtonsoft.json.11.0.2.nupkg
  OK https://api.nuget.org/v3-flatcontainer/newtonsoft.json/11.0.2/newtonsoft.json.11.0.2.nupkg 51ms
Installing Newtonsoft.Json 11.0.2.
Adding package 'Newtonsoft.Json.11.0.2' to folder 'C:\Users\Jack\source\reposd\ConsoleApp1\packages'
Added package 'Newtonsoft.Json.11.0.2' to folder 'C:\Users\Jack\source\reposd\ConsoleApp1\packages'
Added package 'Newtonsoft.Json.11.0.2' to 'packages.config'
Successfully installed 'Newtonsoft.Json 11.0.2' to ConsoleApp1
Executing nuget actions took 2.67 sec
Time Elapsed: 00:00:04.3525244

Program.cs

เปลี่ยน object ให้เป็น string ของ json

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = JsonConvert.SerializeObject(new Result
            {
                id = 1,
                value = "ABC",
                info = "DEF"
            });

            string jsons = JsonConvert.SerializeObject(new
            {
                results = new List<Result>()
                {
                    new Result { id = 2, value = "GHI", info = "JKL" },
                    new Result { id = 3, value = "MNO", info = "PQR" }
                }
            });

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

    public class Result
    {
        public int id { get; set; }
        public string value { get; set; }
        public string info { get; set; }
    }
}

บรรทัดที่ 11-16 จะได้ json

{"id":1,"value":"ABC","info":"DEF"}
{
    "id": 1,
    "value": "ABC",
    "info": "DEF"
}

บรรทัดที่ 18-25 และ jsons

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"JKL","info":"JKL"}]}
{
    "results": [
        {
            "id": 2,
            "value": "GHI",
            "info": "JKL"
        },
        {
            "id": 3,
            "value": "MNO",
            "info": "PQR"
        }
    ]
}

Program.cs

เปลี่ยน string ของ json ให้เป้น object

using Newtonsoft.Json;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string text1 = @"
            {
                'id': 1,
                'value': 'ABC',
                'info': 'DEF'
            }";

            Result result = JsonConvert.DeserializeObject<Result>(text1);

            Console.WriteLine("user.id " + result.id);
            Console.WriteLine("user.value " + result.value);
            Console.WriteLine("user.info " + result.info);
        }
    }

    public class Result
    {
        public int id { get; set; }
        public string value { get; set; }
        public string info { get; set; }
    }
}

ผลการรัน

user.id 1
user.value ABC
user.info DEF

Link

3.การแปลง JSON เป็นคลาส และคลาสเป็น JSON

ติดตั้ง Newtonsoft.Json

PM> Install-Package Newtonsoft.Json -Version 9.0.1

Program.cs

using Newtonsoft.Json;
using System;

namespace ConsoleApplication4
{
    class Product
    {
        public string username { get; set; }
        public string password { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            JsonStringToClass();
            ClassToJsonString();
        }

        static public void JsonStringToClass()
        {
            Console.WriteLine("JsonStringToClass");
            string jsonString = "{\"username\": \"myUser\", ";
            jsonString += "    \"password\": \"myPassword\"}";

            Product result = JsonConvert.DeserializeObject<Product>(jsonString);
            Console.WriteLine("  result.username = " + result.username);
            Console.WriteLine("  result.password = " + result.password);
        }

        static public void ClassToJsonString()
        {
            Console.WriteLine("ClassToJsonString");
            Product result = new Product();
            result.username = "Jack";
            result.password = "secret";

            string jsonString = JsonConvert.SerializeObject(result);
            Console.WriteLine("  jsonString = " + jsonString);
        }
    }
}

บรรทัดที่ 26 : แปลงจาก json string เป็น class
บรรทัดที่ 38 : แปลงจาก class เป็น json string

จะได้

JsonStringToClass
  result.username = myUser
  result.password = myPassword
ClassToJsonString
  jsonString = {"username":"Jack","password":"secret"}