在asp.net中解析Json对象

时间:2014-07-05 12:59:51

标签: c# asp.net json

我在我的Asp.net网络表单的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'?

1 个答案:

答案 0 :(得分:0)

我建议您忘记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);