标签:
假设有如下Json 数据:
1.
{
2.
"id"
: 1,
3.
"@value"
:
"this a @"
,
4.
"$p"
:
"my name a $"
5.
}
1.
public
JsonTest{
2.
public
string
id{
get
;
set
;}
3.
}
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.
}
标签:
原文地址:http://www.cnblogs.com/zcm123/p/4228101.html