JSON 사용하기

2013. 2. 19. 11:31Programming/C#

C#에서 JSON을 객체로 변경할 수 있는 많은 library가 있지만..

일단 .NET Framework에서 제공하는 reference를 사용하기로 한다.

JSON은 .NET Framework 3.5 이상부터 제공하는 기능으로 아래 두 개의 reference를 참조해야 한다.

System.ServiceModel.Web

System.Runtime.Serializations

그 후 아래와 같은 sample code 작성!


[Serializable]
class JsonIn
{
internal string function;
internal string type;
}
[Serializable]
class JsonOut
{
internal string result;
internal string content;
}
class Program
{
static void Main(string[] args)
{
JsonIn jsonIn = new JsonIn();
jsonIn.function = "test";
jsonIn.type = "test";
// Object to Stream
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer dataSerializer = new DataContractJsonSerializer(typeof(JsonIn));
dataSerializer.WriteObject(stream, JsonIn);
// Stream to Object
stream.Position = 0;
JsonIn jsonIn2 = dataSerializer.ReadObject(stream) as JsonIn;
stream.Close();
}
}
view raw gistfile1.cs hosted with ❤ by GitHub