如何在C#Web中解析Json作为开源

时间:2015-10-12 12:01:16

标签: c# asp.net json

net我只是想读一个Json,想要用JSON更新或添加节点。我已经使用了Angular和PHP,我能够轻松地读取和写入文件。但我的服务器现在是IIS,所以我想在C#上解析JSON文件,并希望更改其中的值。

我google了很多,为JSON.NET或Newtonsoft.Json找到了很多解决方案。我只有一个index.aspx页面,我可以成功地读取json文件,如下所示

string json = System.IO.File.ReadAllText(Server.MapPath("json/myJsonFile.json"));
Response.Write(json);

这很容易在网上打印JSON文本。但我无法正确解析它。我在Notepad ++中编写代码,因为我没有Visual Studio而且不想安装。我听说.net代码现在是开源的,所以我从Notepad ++尝试了这个。现在请告诉我,如何在不使用Visual Studio的情况下解析JSON?

我的代码更详细如下

  

的Index.aspx

<%@ Page Language="C#" %>
<!Doctype html>
<html>
<body>
   <form action="index.aspx" method="post" enctype="multipart/form-data" runat="server">
       <input type="text" id="empname" name="empname" placeholder="Enter Full Name"/>
       <p><button id="addBtn" class="btn btn-success" onclick='return addEmployee()' type="submit">Add</button> &nbsp;<button id="removeBtn" class="btn btn-success" onclick='removeEmployee()'>Remove</button></p>
   </form>
<%
   string ename = Request.Form["empname"];
   string json = System.IO.File.ReadAllText(Server.MapPath("json/myJsonFile.json"));
   Response.Write(json);
   //Here i want to parse JSON file
%>
</body>
</html>
  

的Javascript

function addEmployee()
{
  if($("#empname").val() == "")
  {
      alert("Please type Name.");
      $("#empname").focus();
      return false;
   }
   return true;
}
  

JSON

[
   {
    "ID": "ID01",
    "Name": "First One"
   },
   {
     "ID": "ID02",
     "Name": "Second One"
    }
]

记得我在Notepad ++中编写代码,所以请相应地告诉我。提前谢谢。

1 个答案:

答案 0 :(得分:4)

JavaScriptSerializer已被弃用,Microsoft recommends使用Json.NET。

下载Json.NET here

在您的aspx页面链接到Json.NET:

<%@ Assembly Name="Newtonsoft.Json"  %>
<%@ Import namespace="Newtonsoft.Json" %>

为员工创建课程:

public class Employee
{
    public string ID { get; set; }
    public string Name { get; set; }
}

添加对Json.NET的引用:

using Newtonsoft.Json;

从磁盘反序列化您的Json:

List<Employee> list = JsonConvert.DeserializeObject<List<Employee>>(json);

// ...

list.Add(employee);

// deserialize + save
string json = JsonConvert.SerializeObject(list);