在asp.net中解析Json对象
本文关键字:Json 对象 asp net | 更新日期: 2023-09-27 18:11:45
我在我的Asp.net web表单的Page_Load方法中使用了以下代码清单:
var jsonSerializer = new JavaScriptSerializer();
var jsonString = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
var emplList = jsonSerializer.Deserialize<List<Employee>>(jsonString);
var resp = String.Empty;
foreach (var emp in emplList)
{
resp += emp.name + " '' ";
//File.AppendAllText(@"d:'status'LOL.txt", emp.name.ToString()+"'r'n", Encoding.UTF8);
}
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(jsonSerializer.Serialize(resp));
File.AppendAllText(@"d:'status'LOL.txt", resp.ToString() + "'r'n", Encoding.UTF8);
}
catch (Exception)
{
File.AppendAllText(@"d:'status'LOL.txt", "Stop it!", Encoding.UTF8);
}
当我发送JSON到这个aspx文件,对象接收它并将其保存到文件中,读取它,但是我如何使用JSON对象解析变量'resp' ?
我建议您忘记JavaScriptSerializer,而使用newtownsoft的JSON实现。它更快,也很容易使用。使用它的文档在这里:http://james.newtonking.com/json/help/index.html
您可以使用Nuget下载/安装。
下面是一个来自他们文档站点的快速代码片段示例:
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);