C#在Json反序列化中处理键的特殊字符

假设有如下Json 数据:

{
"id" : 1,
"@value" : "this a @",
"$p" : "my name a $"
}
通常情况下,在Json反序列化时,将Json映射到序列化的类,无需指定其名称。如
public JsonTest{
public string id{get;set;}
}

在反序列化时会自动将Json中的ID与类中的ID对应。
但是当键有特殊字符时,如 $ , @ 等,无法定义类的属性中含有特殊字符,
因此,需要使用 [DataContract] 和 [DataMember] 来定义数据协定
 1     [DataContract]
2 public class jtest
3 {
4 [DataMember(Order = 0)]
5 public int id { get; set; }
6 [DataMember(Order = 1, Name = "@value")]
7 public string value { get; set; }
8 [DataMember(Order = 2, Name = "$p")]
9 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);

 
完整测试类:
 1 using System;
2 using System.Text;
3 using System.Runtime.Serialization;
4 using System.Runtime.Serialization.Json;
5 using System.IO;
6
7
8 namespace ConsoleApplication1
9 {
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 }


posted @ 2012-03-27 14:01  翼帆  阅读(8084)  评论(3编辑  收藏  举报