- การติดตั้ง Newtonsoft.Json
- การ Serialize และ Deserialize – Object
- การ Serialize และ Deserialize – Collection
- การ Serialize และ Deserialize – Dictionary
- การ Serialize และ Deserialize – DataSet
- การ Serialize และ Deserialize – DataTable
- การ Deserialize – Anonymous Type
- nuget.org – Newtonsoft.Json
- newtonsoft.com – Serializing JSON
1.การติดตั้ง Newtonsoft.Json
PM> Install-Package Newtonsoft.Json
Installing 'Newtonsoft.Json 12.0.1'. Successfully installed 'Newtonsoft.Json 12.0.1'. Adding 'Newtonsoft.Json 12.0.1' to ConsoleApp1. Successfully added 'Newtonsoft.Json 12.0.1' to ConsoleApp1.
2.การ Serialize และ Deserialize – Object
การ Serialize an Object
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
class Program
{
static void Main(string[] args)
{
Account account = new Account
{
Email = "james@example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
}
};
string json1 = JsonConvert.SerializeObject(account);
Console.WriteLine(json1);
// {"Email":"james@example.com","Active":true,"CreatedDate":"2013-01-20T00:00:00Z","Roles":["User","Admin"]}
string json2 = JsonConvert.SerializeObject(account, Formatting.Indented);
Console.WriteLine(json2);
// {
// "Email": "james@example.com",
// "Active": true,
// "CreatedDate": "2013-01-20T00:00:00Z",
// "Roles": [
// "User",
// "Admin"
// ]
// }
}
}
}
การ Deserialize an Object
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
class Program
{
static void Main(string[] args)
{
string json = @"{
'Email': 'jack@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// jack@example.com
}
}
}
3.การ Serialize และ Deserialize – Collection
การ Serialize a Collection
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
List<string> videogames = new List<string>
{
"Starcraft",
"Halo",
"Legend of Zelda"
};
string json = JsonConvert.SerializeObject(videogames);
Console.WriteLine(json);
// ["Starcraft","Halo","Legend of Zelda"]
}
}
}
การ Deserialize a Collection
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json = @"['Starcraft','Halo','Legend of Zelda']";
List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
Console.WriteLine(string.Join(", ", videogames.ToArray()));
// Starcraft, Halo, Legend of Zelda
}
}
}
4.การ Serialize และ Deserialize – Dictionary
การ Serialize a Dictionary
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> points = new Dictionary<string, int>
{
{ "James", 9001 },
{ "Jo", 3474 },
{ "Jess", 11926 }
};
string json = JsonConvert.SerializeObject(points, Formatting.Indented);
Console.WriteLine(json);
// {
// "James": 9001,
// "Jo": 3474,
// "Jess": 11926
// }
}
}
}
การ Deserialize a Dictionary
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
}";
Dictionary<string, string> htmlAttributes =
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Console.WriteLine(htmlAttributes["href"]);
// /account/login.aspx
Console.WriteLine(htmlAttributes["target"]);
// _blank
}
}
}
5.การ Serialize และ Deserialize – DataSet
การ Serialize a Dataset
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet("dataSet");
ds.Namespace = "NetFrameWork";
DataTable dt = new DataTable();
DataColumn idColumn = new DataColumn("id", typeof(int));
idColumn.AutoIncrement = true;
DataColumn itemColumn = new DataColumn("item");
dt.Columns.Add(idColumn);
dt.Columns.Add(itemColumn);
ds.Tables.Add(dt);
for (int i = 0; i < 2; i++)
{
DataRow newRow = dt.NewRow();
newRow["item"] = "item " + i;
dt.Rows.Add(newRow);
}
ds.AcceptChanges();
string json = JsonConvert.SerializeObject(ds, Formatting.Indented);
Console.WriteLine(json);
// {
// "Table1": [
// {
// "id": 0,
// "item": "item 0"
// },
// {
// "id": 1,
// "item": "item 1"
// }
// ]
// }
}
}
}
การ Serialize ให้ได้ผลลัพธ์เหมือนกับการใช้ Dataset
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Result
{
public int id { get; set; }
public string item { get; set; }
}
class Program
{
static void Main(string[] args)
{
string json = JsonConvert.SerializeObject(new
{
Table1 = new List<Result>()
{
new Result { id = 0, item = "item 0" },
new Result { id = 1, item = "item 1" }
}
}, Formatting.Indented);
Console.WriteLine(json);
//{
// "Table1": [
// {
// "id": 0,
// "item": "item 0"
// },
// {
// "id": 1,
// "item": "item 1"
// }
// ]
//}
}
}
}
การ Deserialize a Dataset
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json = @"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
DataTable dataTable = dataSet.Tables["Table1"];
Console.WriteLine(dataTable.Rows.Count);
// 2
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["id"] + " - " + row["item"]);
}
// 0 - item 0
// 1 - item 1
}
}
}
6.การ Serialize และ Deserialize – DataTable
using Newtonsoft.Json;
using System;
using System.Data;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
DataRow dr1 = dt.NewRow();
dr1["col1"] = "A111";
dr1["col2"] = "A222";
dr1["col3"] = "A333";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["col1"] = "B111";
dr2["col2"] = "B222";
dr2["col3"] = "B333";
dt.Rows.Add(dr2);
string json = JsonConvert.SerializeObject(dt);
Console.WriteLine(json);
//[
// {
// "col1": "A111",
// "col2": "A222",
// "col3": "A333"
// },
// {
// "col1": "B111",
// "col2": "B222",
// "col3": "B333"
// }
//]
DataTable dtResult = JsonConvert.DeserializeObject<DataTable>(json);
Console.WriteLine(dtResult.Rows.Count);
}
}
}
7.การ Deserialize – Anonymous Type
การ Deserialize an Anonymous Type
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var definition = new { Name = "" };
string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.Name);
// James
string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
Console.WriteLine(customer2.Name);
// Mike
}
}
}