Reputation: 3004
I am trying to serialize a List in C# and it is mostly working fine except that it creates backslashes in front of the double quotes. I have read online that this is a result from serializing the data twice and I have tried different approaches to removing the backslashes but they are not really working for me.
C# code (Using NewtonSoft.Json Library):
List<string> list_element_object = new List<string>();
foreach (var list_element in total_lists)
{
/* Code to get all of the 'element_lists' data
Which is eventually used to create the 'columns' data below */
var columns = new Dictionary<string, string>
{
{"@type", "Element_Lists" },
{"Name", Element_List_Name },
{"Description", Element_List_Description},
{"URL", Element_URL }
};
var serialized = JsonConvert.SerializeObject(columns);
// Add the serialized object to the list
list_element_object.Add(serialized);
}
// Serlialize the list containing the data and store into a ViewBag variable to use in a View
ViewBag.Element_Data_Raw = JsonConvert.SerializeObject(list_element_object);
Output:
"{\"@type\":\"Elements\",\"Name\":\"Some_Element_Name\",\"Description\":\"Some_Element_Description\",\"URL\":\"Some_Element_URL\"}"
Expected Output:
"{"@type":"Elements","Name":"Some_Element_Name","Description":"Some_Element_Description","URL":"Some_Element_URL"}"
Any help is greatly appreciated!
Upvotes: 0
Views: 1699
Reputation: 38757
I'm still not 100% certain on your question, but this should produce normal JSON output, which I guess is what you want. As noted by Bagus Tesa in the comments, double quotes will be escaped in the debugger display. Since you're double-serializing a dictionary (i.e. first you're serializing it to a string, and then you're serializing that string), you're bound to have escaped strings in your current output.
List<Dictionary<string, string>> list_element_object = new List<Dictionary<string, string>>();
foreach (var list_element in total_lists)
{
/* Code to get all of the 'element_lists' data
Which is eventually used to create the 'columns' data below */
var Element_List_Name = list_element.Element_List_Name;
var Element_List_Description = list_element.Element_List_Description;
var Element_URL = list_element.Element_URL;
var columns = new Dictionary<string, string>
{
{"@type", "Element_Lists" },
{"Name", Element_List_Name },
{"Description", Element_List_Description},
{"URL", Element_URL }
};
// Add the serialized object to the list
list_element_object.Add(columns);
}
// Serlialize the list containing the data and store into a ViewBag variable to use in a View
ViewBag.Element_Data_Raw = JsonConvert.SerializeObject(list_element_object);
Changing the list to store dictionaries, and then serializing only the list will produce JSON like this (I've formatted it for easy viewing):
[
{
"@type": "Element_Lists",
"Name": "Some_Element_Name",
"Description": "Some_Element_Description",
"URL": "Some_Element_URL"
}
]
Upvotes: 1