我正在开发一个将某些数据写入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对象进行序列化,“导致此问题发生。因为我认为我只序列化了一次,所以它是否与我正在使用Tasks有关还是与它完全有关?
答案 0 :(得分:3)
问题不是反斜杠\
,而是引号"
。
看来您正在序列化的数据已被引用。
如果您可以删除反斜杠,则在输出""
中仍然会用双引号引起来。