我正在开发一个控制台应用程序,它将某些数据写入 JSON 文件。问题在于 VS 用于转义字符串中字符的反斜杠被写入文件中。我确实在 stackoverflow 上发现了类似的问题,但那个人序列化了两次,导致了问题。我认为我的情况并非如此(除非我遗漏了一些东西),这就是为什么我在这里创建了一个单独的问题。
我尝试过执行 string.Replace("\","") 但由于反斜杠实际上并不存在(因为它只是 VS 转义双引号),所以这没有帮助。
我有一个名为 listItem 的类,它有一些属性;
class ListItem
{
public string title;
public string textline;
public string docuType;
}
我有一个 SPList 类,其中包含这些 ListItems 的列表;
class SPList
{
public string listTitle;
public List<ListItem> listItems;
}
我有一个使用 2 个列表将内容写入 JSON 文件的示例;
[
{
"listTitle": "\"Another List\"",
"listItems": [
{
"title": "\"Here\"",
"textline": "\"Another test value\"",
"docuType": null
},
{
"title": "\"Look at this\"",
"textline": "\"It's another value for testing\"",
"docuType": null
}
]
},
{
"listTitle": "\"Sample List\"",
"listItems": [
{
"title": "\"Sample value\"",
"textline": null,
"docuType": "\"Analyse\""
},
{
"title": "\"Sample value 2\"",
"textline": null,
"docuType": "\"IetsAnders\""
},
{
"title": "\"SampleValue3!\"",
"textline": null,
"docuType": "\"Offerte\""
}
]
}
]
最后,我用来实现这一点的代码;
Task <List<string>>listIDs = GetListIDs();
listIDs.Wait();
foreach (string id in listIDs.Result)
{
Task<string> lijstTitel = GetListTitle(id);
lijstTitel.Wait();
Task<List<string>> listitemIDs = GetItemIDs(id);
listitemIDs.Wait();
// Write all the items here
foreach (string itemID in listitemIDs.Result)
{
Task<ListItem> itempje = GetItem(itemID, id);
itempje.Wait();
listItems.Add(itempje.Result);
}
list.Add( new SPList{
listItems = listItems,
listTitle = lijstTitel.Result
});
listItems = new List<ListItem>();
}
string json = JsonConvert.SerializeObject(list, Formatting.Indented);
System.IO.File.WriteAllText(path, json);
在我发现的类似问题的另一个示例中,该人将其 JSON 对象序列化两次,导致此问题发生。因为我认为我只序列化它一次,所以它与我使用任务的事实有关还是完全是其他东西?
最佳答案
问题不是反斜杠\
,而是引号"
。
看来您正在序列化的数据已被引用。
如果您可以删除反斜杠,输出中仍然会出现双引号 ""
。
关于C# 将 JSON 写入不带反斜杠的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58214285/