如何将JSON格式序列化为新的JSON文件?

时间:2017-11-24 03:31:14

标签: c# asp.net json

我想将c#中的这个json格式保存到我的计算机中的json文件中以进行离线工作。 我有像这样的Json格式

    {
        "Name": "room 1",
        "TimeOpen": "6:30AM — 11:30PM",
        "Phone": "(0) 66 11111",
        "Description": "Hospital Room 1",
        "Image": "1.jpg",
        "RoomNumber": "1",
        "DepartmentType": 1,
        "Direction": "First Room of Floor 1",
        "Floor": "1"
    },
    {
        "Name": "room 2",
        "TimeOpen": "10:15AM - 8:30PM",
        "Phone": "(0) 66 5738902",
        "Description": "Hospital Room 2",
        "Image": "2.jpg",
        "RoomNumber": "2",
        "DepartmentType": 2,
        "Direction": "Second Room of Floor 1",
        "Floor": "1"
    },
    {
        "Name": "room 3",
        "TimeOpen": "7:30AM — 16:30PM",
        "Phone": "(0) 66 5738902",
        "Description": "Hospital Room 3",
        "Image": "3.jpg",
        "RoomNumber": "3",
        "DepartmentType": 2,
        "Direction": "Third room of Floor 1",
        "Floor": "1"
    },

在课堂上是:

public class HosRoomViewModel
    {
        public string Name { get; set; }
        public string TimeOpen { get; set; }
        public string Phone { get; set; }
        public string Description { get; set; }
        public string Image { get; set; }
        public string RoomNumber { get; set; }
        public int DepartmentType { get; set; }
        public string Direction { get; set; }
        public string Floor { get; set; }
    }

在客户端项目中,我使用它来调用此API

public ActionResult HospitalMap(Guid hosId)
    {
        string apiRequest = string.Format("api/bv/DetailHospital?hosId={0}", hosId);
        var client = new RestClient("http://localhost:9666");
        var req = new RestRequest(apiRequest, Method.GET) {RequestFormat = DataFormat.Json};
        var rs = client.Execute<HttpContentResultPaged<List<HosRoomViewModel>>>(req).Data;
        var listApp = rs.Data;
        string jsondata = new JavaScriptSerializer().Serialize(listApp);
        string path = Server.MapPath("~App_Data/");
        System.IO.File.WriteAllText(path + "room.json", jsondata);
        TempData["msg"] = "Json file Generated! check this in your App_Data folder";

        return View(listApp);
    }

但是当我运行我的项目时出现此错误: Could not find a part of the path: 'C:...\room.json' 如果您想了解更多信息,请告诉我。

2 个答案:

答案 0 :(得分:1)

您在Server.MapPath中使用了错误的路径。尝试:

string path = Server.MapPath("~/App_Data/");

答案 1 :(得分:0)

您可以将List转换为Text文件,以下列方式保持JSON对象的完整性

using (StreamWriter file = File.CreateText(@"D:\FILENAME.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, listApp );
}