在C#中将列表序列化为JSON在引号前面创建反斜杠

时间:2018-07-02 00:29:14

标签: c# json json.net

我正在尝试序列化C#中的List,并且除了在双引号前面创建反斜杠之外,它几乎可以正常工作。我已经在线阅读了这是由于对数据进行两次序列化的结果,并且我尝试了各种方法来消除反斜杠,但它们对我而言并不是真正的工作。

C#代码(使用NewtonSoft.Json库):

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);

输出:

"{\"@type\":\"Elements\",\"Name\":\"Some_Element_Name\",\"Description\":\"Some_Element_Description\",\"URL\":\"Some_Element_URL\"}"

预期输出:

"{"@type":"Elements","Name":"Some_Element_Name","Description":"Some_Element_Description","URL":"Some_Element_URL"}"

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

对于您的问题,我仍然不确定100%,但这应该会产生正常的JSON输出,我想这就是您想要的。正如Bagus Tesa在评论中指出的那样,调试器的显示中将转义双引号。由于您要对字典进行双序列化(即首先将其序列化为一个字符串,然后序列化该字符串),所以您肯定会在当前输出中转义了字符串。

            Maybe   No    Yes
Question1   2.0     2.0   0.0
Question2   2.0     0.0   2.0
Question3   1.0     1.0   2.0

更改列表以存储字典,然后仅对列表进行序列化将生成如下所示的JSON(为了方便查看,我对其进行了格式化):

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);

Try it online