ASP.NET 利用DataContractJsonSerializer序列化和反序列化
public T JsonDeserialize(string jsonString) { if (!string.IsNullOrEmpty(jsonString)) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); ms.Close(); return obj; } else { return default(T); } } public string JsonSerializer(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; }
将字符串转为数组并json序列化
string usersString = "zhangsan,lisi,wangwu"; string[] sArray = usersString.Split(','); List<ChatUserName> listUser = new List<ChatUserName>(); for (int i = 0; i < sArray.Length; i++) { listUser.Add(new ChatUserName() { name = sArray[i] }); } usersJson = JsonSerializer(listUser);
将json字符串反序列化为List数组
List<ChatUserName> chatUserList = JsonDeserialize<List<ChatRooms>>(chatUserJson);
页面中显示每个用户的名字
foreach(ChatUserName chatUserName in chatUserList){ //chatUserName.name 这个就是用户的名字 //chatUserName.nickname 就是用户的名称,显然这里只用的name,不存在nickname }
定义 ChatUserName类
public class ChatUserName { public string name { get; set; } public string nickname { get; set; } }
(673)