-
假设有如下Json 数据:
1.
{
2.
"id"
: 1,
3.
"@value"
:
"this a @"
,
4.
"$p"
:
"my name a $"
5.
}
通常情况下,在Json反序列化时,将Json映射到序列化的类,无需指定其名称。如
1.
public
JsonTest{
2.
public
string
id{
get
;
set
;}
3.
}
在反序列化时会自动将Json中的ID与类中的ID对应。但是当键有特殊字符时,如 $ , @ 等,无法定义类的属性中含有特殊字符,因此,需要使用 [DataContract] 和 [DataMember] 来定义数据协定。01.
[DataContract]
02.
public
class
jtest
03.
{
04.
[DataMember(Order = 0)]
05.
public
int
id {
get
;
set
; }
06.
[DataMember(Order = 1, Name =
"@value"
)]
07.
public
string
value {
get
;
set
; }
08.
[DataMember(Order = 2, Name =
"$p"
)]
09.
public
string
_p {
get
;
set
; }
10.
}
反序列化1.
jtest test = serializer.ReadObject(
new
MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
as
jtest;
2.
Console.WriteLine( test.value );
序列化
1.
var stream =
new
MemoryStream();
2.
serializer.WriteObject(stream, test);
3.
byte
[] dataBytes =
new
byte
[stream.Length];
4.
stream.Position = 0;
5.
stream.Read(dataBytes, 0, (
int
)stream.Length);
6.
string
dataString = Encoding.UTF8.GetString(dataBytes);
完整测试类:01.
using
System;
02.
using
System.Text;
03.
using
System.Runtime.Serialization;
04.
using
System.Runtime.Serialization.Json;
05.
using
System.IO;
06.
07.
08.
namespace
ConsoleApplication1
09.
{
10.
class
Program
11.
{
12.
static
void
Main(
string
[] args)
13.
{
14.
string
jsonStr =
"{\"id\":1,\"@value\":\"this a @\",\"$p\":\"my name a $\"}"
;
15.
DataContractJsonSerializer serializer =
new
DataContractJsonSerializer(
typeof
(jtest));
16.
17.
//反序列化
18.
jtest test = serializer.ReadObject(
new
MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
as
jtest;
19.
Console.WriteLine( test.value );
20.
21.
//序列化
22.
var stream =
new
MemoryStream();
23.
serializer.WriteObject(stream, test);
24.
byte
[] dataBytes =
new
byte
[stream.Length];
25.
stream.Position = 0;
26.
stream.Read(dataBytes, 0, (
int
)stream.Length);
27.
string
dataString = Encoding.UTF8.GetString(dataBytes);
28.
29.
Console.WriteLine(dataString);
30.
Console.ReadKey();
31.
}
32.
}
33.
[DataContract]
34.
public
class
jtest
35.
{
36.
[DataMember(Order = 0)]
37.
public
int
id {
get
;
set
; }
38.
[DataMember(Order = 1, Name =
"@value"
)]
39.
public
string
value {
get
;
set
; }
40.
[DataMember(Order = 2, Name =
"$p"
)]
41.
public
string
_p {
get
;
set
; }
42.
}
43.
}
相关文章
- 08-16C#在Json反序列化中处理键的特殊字符
- 08-16C#在Json反序列化中处理键的特殊字符