gpt4 book ai didi

c# - 我可以在 Xamarin、C#、iOS 中保存对象数组(或 json 数组、字典数组)吗?

转载 作者:行者123 更新时间:2023-11-28 21:30:37 24 4
gpt4 key购买 nike

我有一个“app”对象列表,我想将其保存到文件中并稍后检索。我必须使用“File.AppendAllText(filename, son)”将每个对象保存到文件中,但是在检索文件时它会抛出以下异常:

保存到文件:

var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine (documents, "app.json");
for (int i = 0; i < 25; i++) {
nuint index = (nuint)i;
App app = appsArray.GetItem<App>(index);
var json = JsonConvert.SerializeObject (app, Newtonsoft.Json.Formatting.Indented);
File.AppendAllText(filename, json);
}

从文件中读取:

    var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine (documents, "app.json");
String text = File.ReadAllText (filename);
Console.WriteLine ("text: {0}", text);
App appJSON = (App)Newtonsoft.Json.JsonConvert.DeserializeObject (text);

在反序列化时检索文件时中断:“抛出了 Newtonsoft.Json.JsonReaderException:”"读完JSON内容后遇到的附加文本:{.Path'', line 14, position 1. "

文本输出为:

2016-03-24 18:14:47.405 top25[30102:2442745] text: { "Title": "Basketball Stars™", "Summary": "The world’s best multiplayer Basky", "AppIcon": { "ClassHandle": {}, "SuperHandle": {}, "Handle": {} }, "AppIconURLString": "http://is2.mzstatic.com/image/thumb/Purple49/v4/71/1e/ad/711ead80-6f18-3b46-2947-85c4d7b38292/mzl.qvwejzyt.png/53x53bb-85.png", "Rank": 1, "SuperHandle": {}, "Handle": {}, "ClassHandle": {} }{ "Title": "Snapchat", "Summary": "Life's more fun when you live in the moment :) Happy Snapping!\n\n* * *\n\nPlease note: Snapchatters can always capture or save your messages, such as by taking a screenshot or using a camera. Be mindful of what you Snap!", "AppIcon": { "ClassHandle": {}, "SuperHandle": {}, "Handle": {} }, "AppIconURLString": "http://is1.mzstatic.com/image/thumb/Purple49/v4/ea/1c/21/ea1c2133-acbd-c16f-a8d5-33e254fdab7b/mzl.xydsraya.png/53x53bb-85.png", "Rank": 2, "SuperHandle": {}, "Handle": {}, "ClassHandle": {} }

最佳答案

您正在序列化每个单独的对象并将其附加到一个文件,这会创建无效的 JSON。相反,您应该只序列化整个数组并写入一次。

var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine (documents, "app.json");
var json = JsonConvert.SerializeObject (appsArray, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filename, json);

关于c# - 我可以在 Xamarin、C#、iOS 中保存对象数组(或 json 数组、字典数组)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com