JSON.NET        
    
                    JSON.NET은 .NET에서 JSON을 사용하기 위해 가장 널리 사용되는 오픈 소스이다.         JSON.NET은 현재 DLL을 별도로 설치해야 한다는 단점이 있지만, JavaScriptSerializer 나        DataContractJsonSerializer에 비해 훨씬 많은 Feature를 가지고 있고, 특히 LINQ를 사용할 수 있는        기능을 제공하고 있다.
JSON.NET을 사용하기 위해서는 (1) http://james.newtonking.com/json 에서 다운 받거나 (2) NuGet을 사용하여 프로젝트에 직접 다운 받는다.
james.newtonking.com 웹사이트에서 다운받는 경우는 .NET 2.0 부터 다양한 .NET 버젼이 있으므로 C# 프로젝트의 해당 .NET Framework 버젼에 맞는 것을 Reference에 추가한다. NuGet에 설치하는 경우는 C# 프로젝트의 .NET Framework 버젼에 맞는 것을 자동으로 추가해 준다.
        
    JSON.NET을 사용하기 위해서는 (1) http://james.newtonking.com/json 에서 다운 받거나 (2) NuGet을 사용하여 프로젝트에 직접 다운 받는다.
james.newtonking.com 웹사이트에서 다운받는 경우는 .NET 2.0 부터 다양한 .NET 버젼이 있으므로 C# 프로젝트의 해당 .NET Framework 버젼에 맞는 것을 Reference에 추가한다. NuGet에 설치하는 경우는 C# 프로젝트의 .NET Framework 버젼에 맞는 것을 자동으로 추가해 준다.
            //NuGet에서 설치할 경우
PM> install-package Newtonsoft.Json
                    PM> install-package Newtonsoft.Json
        JSON.NET 사용        
    
                    JSON.NET 사용을 위해서는 먼저 설치 후, Newtonsoft.Json.dll을 Reference에 추가하고,         C# 코드에서 using Newtonsoft.Json 을 추가한다.         JSON.NET은 많은 Feature들을 가지고 있지만, 여기서는 간단한 시나리오만을 일단 소개한다.        .NET 객체로부터 JSON 문자열을 만들기 위해서는 JsonConvert.SerializeObject() 메서드를 사용한다.        또한 JSON 문자열로부터 .NET 객체를 다시 복원하기 위해서는 JsonConvert.DeserializeObject<T>() 메서드를 사용한다.                
        
         예제
    namespace jsonApp
{
// 1. JSON.NET 설치 (NuGet)
// PM> install-package Newtonsoft.Json
//
// 2. Newtonsoft.Json.dll 참조 (.NET 버젼별로 다름)
using Newtonsoft.Json;
    
// JSON.NET 를 이용한 Json 예제
class JsonUsingJSONNET
{
public void DoTest()
{
// 2. JSON string 만들기
var p = new Person { Id = 1, Name = "Alex" };
string jsonString = JsonConvert.SerializeObject(p);
System.Diagnostics.Debug.WriteLine(jsonString);
// 3. JSON string으로부터 Object 가져오기
Person pObj = JsonConvert.DeserializeObject<Person>(jsonString);
System.Diagnostics.Debug.WriteLine(pObj.Name);
}
}
}
    
            {
// 1. JSON.NET 설치 (NuGet)
// PM> install-package Newtonsoft.Json
//
// 2. Newtonsoft.Json.dll 참조 (.NET 버젼별로 다름)
using Newtonsoft.Json;
// JSON.NET 를 이용한 Json 예제
class JsonUsingJSONNET
{
public void DoTest()
{
// 2. JSON string 만들기
var p = new Person { Id = 1, Name = "Alex" };
string jsonString = JsonConvert.SerializeObject(p);
System.Diagnostics.Debug.WriteLine(jsonString);
// 3. JSON string으로부터 Object 가져오기
Person pObj = JsonConvert.DeserializeObject<Person>(jsonString);
System.Diagnostics.Debug.WriteLine(pObj.Name);
}
}
}
        LINQ to JSON과 dynamic 사용법        
    
                    JSON.NET은 LINQ를 사용할 수 있는 LINQ to JSON 기능을 추가하였다.        LINQ to JSON은 Newtonsoft.Json.Linq 네임스페이스 안에 있는데,        JSON의 특정 노드 값을 선택적으로 읽거나 새로운 JSON 을 만들때 유용하게 사용될 수 있다.
아래 예제 (1)은 JSON 문자열을 파싱한 후 LINQ 를 사용한 예이다. JObject.Parse() 메서드는 JSON 문자열을 파싱하여 JSON 전체를 갖는 JObject 객체를 리턴한다. 이 JObject 객체로부터 각 노드들을 인덱서를 통해 엑세스하여 JToken 객체를 얻을 수 있으며, LINQ 쿼리를 사용하여 노드들로부터 필요한 데이타를 발췌할 수 있다. LINQ to JSON은 위의 JsonConvert.DeserializeObject<T>() 처럼 데이타 타입을 미리 C# 클래스로 지정하지 않을 경우 유용하게 사용될 수 있다.
미리 C# 데이타 타입을 지정하지 않는 또 다른 방식으로 JsonConvert.DeserializeObject() 메서드를 사용하여 Deserialize된 dynamic 객체를 얻는 방법이 있다. dynamic 객체를 얻은 후에는 동적으로 하위 노드들을 직접 엑세스할 수 있다. 아래 예제 (2)가 이러한 용법을 예시한 것이다.
        
         아래 예제 (1)은 JSON 문자열을 파싱한 후 LINQ 를 사용한 예이다. JObject.Parse() 메서드는 JSON 문자열을 파싱하여 JSON 전체를 갖는 JObject 객체를 리턴한다. 이 JObject 객체로부터 각 노드들을 인덱서를 통해 엑세스하여 JToken 객체를 얻을 수 있으며, LINQ 쿼리를 사용하여 노드들로부터 필요한 데이타를 발췌할 수 있다. LINQ to JSON은 위의 JsonConvert.DeserializeObject<T>() 처럼 데이타 타입을 미리 C# 클래스로 지정하지 않을 경우 유용하게 사용될 수 있다.
미리 C# 데이타 타입을 지정하지 않는 또 다른 방식으로 JsonConvert.DeserializeObject() 메서드를 사용하여 Deserialize된 dynamic 객체를 얻는 방법이 있다. dynamic 객체를 얻은 후에는 동적으로 하위 노드들을 직접 엑세스할 수 있다. 아래 예제 (2)가 이러한 용법을 예시한 것이다.
예제
    using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string str = @"{
Id: 101,
Phone: ['010-123-3456', '02-2222-3333', '010-222-1121']
}";
// 예제 1 : LINQ to JSON
// JSON 문자열을 파싱하여 JObject를 리턴
JObject jo = JObject.Parse(str);
// JObject 인덱서를 사용하여 특정 Token을 리턴
JToken idToken = jo["Id"];
int id = (int)idToken;
string phone1 = jo["Phone"][0].ToString();
Console.WriteLine("{0}:{1}", id, phone1);
var cell = jo["Phone"].Select(p => p.ToString().StartsWith("010"));
// 예제 2 : dynamic
dynamic jobj = JsonConvert.DeserializeObject(str);
var xid = jobj.Id.ToString();
var xphone1 = jobj.Phone[1].ToString();
Console.WriteLine("{0}:{1}", xid, xphone1);
}
}
            using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string str = @"{
Id: 101,
Phone: ['010-123-3456', '02-2222-3333', '010-222-1121']
}";
// 예제 1 : LINQ to JSON
// JSON 문자열을 파싱하여 JObject를 리턴
JObject jo = JObject.Parse(str);
// JObject 인덱서를 사용하여 특정 Token을 리턴
JToken idToken = jo["Id"];
int id = (int)idToken;
string phone1 = jo["Phone"][0].ToString();
Console.WriteLine("{0}:{1}", id, phone1);
var cell = jo["Phone"].Select(p => p.ToString().StartsWith("010"));
// 예제 2 : dynamic
dynamic jobj = JsonConvert.DeserializeObject(str);
var xid = jobj.Id.ToString();
var xphone1 = jobj.Phone[1].ToString();
Console.WriteLine("{0}:{1}", xid, xphone1);
}
}
JSON.NET과 JavaScriptSerializer, DataContractJsonSerializer 비교
(이 비교표는 JSON.NET 웹사이트 http://james.newtonking.com 에서 (2014년 8월 현재) 발췌된 것으로 최신 비교표는 JSON.NET 사이트를 참조)
| Json.NET | DataContractJsonSerializer | JavaScriptSerializer | |
|---|---|---|---|
| Supports JSON |  |  |  | 
| Supports BSON |  |  |  | 
| Supports JSON Schema |  |  |  | 
| Supports .NET 2.0 |  |  |  | 
| Supports .NET 3.5 |  |  |  | 
| Supports .NET 4.0 |  |  |  | 
| Supports Silverlight |  |  |  | 
| Supports Windows Phone |  |  |  | 
| Open Source |  |  |  | 
| MIT License |  |  |  | 
| LINQ to JSON |  |  |  | 
| Thread Safe |  |  |  | 
| XPath-like JSON query syntax |  |  |  | 
| Indented JSON support |  |  |  | 
| Efficient dictionary serialization |  |  |  | 
| Nonsensical dictionary serialization |  |  |  | 
| Deserializes IList, IEnumerable, ICollection, IDictionary properties |  |  |  | 
| Serializes circular references |  |  |  | 
| Supports serializing objects by reference |  |  |  | 
| Deserializes polymorphic properties and collections |  |  |  | 
| Supports including type names with JSON |  |  |  | 
| Globally customize serialization process |  |  |  | 
| Supports excluding null values when serializing |  |  |  | 
| Supports SerializationBinder |  |  |  | 
| Conditional property serialization |  |  |  | 
| Includes line number information in errors |  |  |  | 
| Converts XML to JSON and JSON to XML |  |  |  | 
| JSON Schema validation |  |  |  | 
| JSON Schema generation from .NET types |  |  |  | 
| Camel case JSON property names |  |  |  | 
| Non-default constructors support |  |  |  | 
| Serialization error handling |  |  |  | 
| Supports populating an existing object |  |  |  | 
| Efficiently serializes byte arrays as base64 text |  |  |  | 
| Handles NaN, Infinity, -Infinity and undefined |  |  |  | 
| Handles JavaScript constructors |  |  |  | 
| Serializes .NET 4.0 dynamic objects |  |  |  | 
| Serializes ISerializable objects |  |  |  | 
| Supports serializing enums to their text name |  |  |  | 
| JSON recursion limit support |  |  |  | 
| Attribute property name customization |  |  |  | 
| Attribute property order customization |  |  |  | 
| Attribute property required customization |  |  |  | 
| Supports ISO8601 dates |  |  |  | 
| Supports JavaScript constructor dates |  |  |  | 
| Supports Microsoft AJAX dates |  |  |  | 
| Unquoted property names support |  |  |  | 
| Raw JSON support |  |  |  | 
| Supports reading and writing comments |  |  |  | 
| Deserializes anonymous types |  |  |  | 
| Opt-in property serialization |  |  |  | 
| Opt-out property serialization |  |  |  | 
| Efficiently stream reading and writing JSON |  |  |  | 
| Single or double quote JSON content |  |  |  | 
| Supports overriding a type's serialization |  |  |  | 
| Supports OnDeserialized, OnSerializing, OnSerialized and OnDeserializing attributes |  |  |  | 
| Supports serializing private properties |  |  |  | 
| DataMember attribute support |  |  |  | 
| MetdataType attribute support |  |  |  | 
| DefaultValue attribute support |  |  |  | 
| Serializes DataSets and DataTables |  |  |  | 
| Serailizes Entity Framework |  |  |  | 
| Serializes nHibernate |  |  |  | 
| Case-insensitive property deserialization |  |  |  |