VB.net 如何解析Json
string json ={
"name": "Jack",
"email": "email@163.com"}
Public Class user
Private _name As String
Public Property name As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _email As String
Public Property email As String
Get
Return _email
End Get
Set(ByVal value As String)
_email = value
End Set
End Property
End Class
public static void JavaScriptSerializerDemo()
{
User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30),Birthday=DateTime.Now.AddYears(-50), Priority = Priority.Highest, Salary = 500000 };
//JavaScriptSerializer类在System.Web.Extensions.dll中,注意添加这个引用
JavaScriptSerializer serializer = new JavaScriptSerializer();
//JSON序列化
string result=serializer.Serialize(user);
Console.WriteLine("使用JavaScriptSerializer序列化后的结果:{0},长度:{1}", result, result.Length);
//JSON反序列化
user = serializer.Deserialize<User>(result);
Console.WriteLine("使用JavaScriptSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority);
}
下面是使用Newtonsoft.Json.JsonConvert类的例子
public static void JsonConvertDemo()
{
User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30), Birthday = DateTime.Now.AddYears(-50), Priority = Priority.BelowNormal, Salary = 5000 };
//JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvert.SerializeObject(user);
Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length);
//JSON反序列化
user = JsonConvert.DeserializeObject<User>(result);
Console.WriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority);
}
public static void JsonConvertLinqDemo()
{
User user = new User { UserId = 1, UserName = "周公", CreateDate = DateTime.Now.AddYears(-8), Birthday = DateTime.Now.AddYears(-32), Priority = Priority.Lowest, Salary = 500, Urls = new List<string> { "http://zhoufoxcn.blog.51cto.com", "http://blog.csdn.net/zhoufoxcn" } };
//JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvert.SerializeObject(user);
Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length);
//使用Linq to JSON
JObject jobject = JObject.Parse(result);
JToken token = jobject["Urls"];
List<string> urlList = new List<string>();
foreach (JToken t in token)
{
urlList.Add(t.ToString());
}
Console.Write("使用Linq to JSON反序列化后的结果:[");
for (int i = 0; i < urlList.Count - 1;i++ )
{
Console.Write(urlList[i] + ",");
}
Console.WriteLine(urlList[urlList.Count - 1] + "]");
}