1 static void Main(string[] args) 2 { 3 Models m = new Models() { a = "1", b = "2" }; 4 string json=JsonSerializer<Models>(m); 5 Console.WriteLine(json); 6 //输出结果:b在a前边 7 //{"b":"2","a":"1"} 8 } 9 //自定义类 10 [DataContract] 11 public class Models 12 { 13 //Order索引从0开始,越小越靠前 14 [DataMember(Order = 2)] 15 public string a { get; set; } 16 [DataMember(Order = 1)] 17 public string b { get; set; } 18 19 } 20 //JSON序列化 21 public static string JsonSerializer<T>(T t) 22 { 23 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 24 MemoryStream ms = new MemoryStream(); 25 ser.WriteObject(ms, t); 26 string jsonString = Encoding.UTF8.GetString(ms.ToArray()); 27 ms.Close(); 28 return jsonString; 29 } 30 /// <summary> 31 /// JSON反序列化 32 /// </summary> 33 public static T JsonDeserialize<T>(string jsonString) 34 { 35 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 36 MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); 37 T obj = (T)ser.ReadObject(ms); 38 return obj; 39 }