Quick JSON Serialization/Deserialization in C#
You don’t need to download an additional libraryto serialize/deserialize your objects to/from JSON. Since .NET 3.5, .NET can do it natively.
Add a reference to your project to “System.Web.Extensions.dll”
Let’s look at this example JSON string:
1
{
2
"some_number"
: 108.541,
3
"date_time"
:
"2011-04-13T15:34:09Z"
,
4
"serial_number"
:
"SN1234"
5
}
You can deserialize the previous JSON into a dictionary like so:
1
using
System.Web.Script.Serialization;
2
3
var jss =
new
JavaScriptSerializer();
4
var dict = jss.Deserializestring
,
string
>>(jsonText);
5
6
Console.WriteLine(dict[
"some_number"
]);
//outputs 108.541
So what if your JSON is a bit more complex? 1
{
2
"some_number"
: 108.541,
3
"date_time"
:
"2011-04-13T15:34:09Z"
,
4
"serial_number"
:
"SN1234"
5
"more_data"
: {
6
"field1"
: 1.0
7
"field2"
:
"hello"
8
}
9
}
Deserialize like so… 1
using
System.Web.Script.Serialization;
2
3
var jss =
new
JavaScriptSerializer();
4
var dict = jss.Deserializestring
,dynamic>>(jsonText);
5
6
Console.WriteLine(dict[
"some_number"
]);
//outputs 108.541
7
Console.WriteLine(dict[
"more_data"
][
"field2"
]);
//outputs hello
The field “more_data” gets deserialized into a Dictionary.
You can actually just just deserialize like so: 1
using
System.Web.Script.Serialization;
2
3
var jss =
new
JavaScriptSerializer();
4
var dict = jss.Deserialize(jsonText);
5
6
Console.WriteLine(dict[
"some_number"
]);
//outputs 108.541
7
Console.WriteLine(dict[
"more_data"
][
"field2"
]);
//outputs hello
And everything still works the same. The only caveat is that you lose intellisense by using the “dynamic” data type.
Serialization is just as easy: 1
using
System.Web.Script.Serialization;
2
3
var jss =
new
JavaScriptSerializer();
4
var dict = jss.Deserialize(jsonText);
5
6
var json = jss.Serialize(dict);
7
Console.WriteLine(json);
Outputs… 1
{
2
"some_number"
: 108.541,
3
"date_time"
:
"2011-04-13T15:34:09Z"
,
4
"serial_number"
:
"SN1234"
5
"more_data"
: {
6
"field1"
: 1.0
7
"field2"
:
"hello"
8
}
9
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
AS를 통한 Module 개발1. ModuleLoader 사용 2. IModuleInfo 사용 ASModuleOne 모듈...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.