我正在開發一個佇列管理系統應用程式,當柜臺上的人按下呼叫下一個按鈕時,我的程式使用他們的 ID 獲取下一個人的詳細資訊并將它們保存到一個 JSON 檔案中,然后由顯示他們的頁面讀取名稱、ID 和圖片。現在我可以保存單個資料,但是當我保存另一個值時,JSON 檔案顯示“只允許一個頂級專案”
List<ServerToScreen> ScreenData = new List<ServerToScreen>()
{
new ServerToScreen()
{
StudentID=StudentId,
Name = StudentDetails.StudentName,
Photo =StudentDetails.Photo!=null? Convert.ToBase64String( StudentDetails.Photo):NoProfilePic,
HallNo = Result.Where(x=>x.RegisNumber==StudentId).FirstOrDefault().HALLNumber,
TvIP = Result.Where(x=>x.RegisNumber==StudentId).FirstOrDefault().TVIPAddress,
IsCalledOnScreen=false
}
};
string ServerToJson = new JavaScriptSerializer().Serialize(ScreenData);
string path = Server.MapPath("~/TvScreenData/");
System.IO.File.AppendAllText(path "output.json", ServerToJson);
這是將資料寫入 JSON 檔案的代碼部分,這是我用于相同的模型
public class ServerToScreen {
public string StudentID { get; set; }
public string Name { get; set; }
public string Photo { get; set; }
public string HallNo { get; set; }
public string TvIP { get; set; }
public bool IsCalledOnScreen { get; set; }
}
以及它創建的 JSON
[
{
"StudentID": "09292",
"Name": "brad pit Aman",
"Photo": "null",
"HallNo": "1",
"TvIP": "192.0.0.1",
"IsCalledOnScreen": false
}
]
[
{
"StudentID": "282828",
"Name": "mani a mani",
"Photo": "null",
"HallNo": "1",
"TvIP": "192.0.0.1",
"IsCalledOnScreen": false
}
]
現在我在某處讀到我必須將串列保存為 obj1,obj2 雖然我明白這意味著我無法弄清楚如何去做,我真的被困住了,所以任何幫助都會很棒,謝謝。
uj5u.com熱心網友回復:
該問題是由于每次呼叫此方法時向檔案中添加一個新的 json 串列引起的。
你想要做的是首先從這個檔案中將json串列加載到你的csharp代碼中,然后將新的ServerToScreen物件添加到加載的串列中,然后用新串列替換json檔案。
代碼示例:
ServerToScreen newObject = new ServerToScreen() {
// create the new ServerToScreen object with all properties
}
var serializer = new JavaScriptSerializer();
string outputPath = Server.MapPath("~/TvScreenData/") "output.json";
// Load current list from the file
string currentList = System.IO.File.ReadAllText(outputPath);
List<ServerToScreen> screenData = serializer.Deserialize<List<ServerToScreen>>(currentList);
// Add the new object to this list
screenData.Add(newObject);
// Serialize the list including the new object, and replace the file
string jsonWithNewObject = serializer.Serialize(screenData);
System.IO.File.WriteAllText(outputPath, jsonWithNewObject);
注意:代碼未經測驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403363.html
標籤:
