使用 ExpandoObject 和 IDictionary 从动态 JSON 中删除转义字符 '\'

Remove Escape Character '\' from dynamic JSON using ExpandoObject and IDictionary

我正在使用 ExpandoObject 和 IDictionary 创建动态 JSON。

我的示例代码如下:

DataTable dt_MappedColumns = new DataTable();
    dt_MappedColumns.Columns.Add("Sr.No");
    dt_MappedColumns.Columns.Add("TColumnName");
    dt_MappedColumns.Columns.Add("AColumnName");
    dt_MappedColumns.Rows.Add("1", "Apple", "Lion");
    dt_MappedColumns.Rows.Add("2", "Orange", "Tiger");
    dt_MappedColumns.Rows.Add("3", "Mango", "Fox");
    dt_MappedColumns.Rows.Add("4", "Orange", "Wolf");

    var dictionary1 = new Dictionary<string, object>();
    foreach (DataRow dr in dt_MappedColumns.Rows)
    {
        string key = dr["TColumnName"].ToString();
        string value = dr["AColumnName"].ToString();

        if (!dictionary1.ContainsKey(key))
        {
            // key does not already exist, so add it
            dictionary1.Add(key, value);
        }
        else
        {
            // key exists, get the existing value
            object existingValue = dictionary1[key];

            if (existingValue is string)
            {
                // replace the existing string value with a list
                dictionary1[key] = new List<string> { (string)existingValue, value }; 
            }
            else
            {
                // the existing value is a list, so just add the new value to it
                ((List<string>)existingValue).Add(value);
            }
        }
    }

    string Manjson = JsonConvert.SerializeObject(dictionary1);

这样得到的JSON字符串如下,带转义字符{\}:

"{\"Apple\":\"Lion\",\"Orange\":[\"Tiger\",\"Wolf\"],\"Mango\":\"Fox\"}".

我希望删除转义字符 {\} 并且希望 JSON 如下所示:

"{"Apple":"Lion", "Orange":["Tiger","Wolf"], "Mango":"Fox"}"

**** 编辑 ****

有趣的是,如果我在控制台中打印 JSON,它没有转义字符,但是当我插入 Oracle DB Table 时,它插入了转义字符。

将 Visual Studio 2010 Professional 与 Oracle 11g 和 PL/SQL 11.2

结合使用

解决这个问题的方法是什么:

感谢任何帮助:)

我通过将其转换为 JObject 然后按如下方式使用它来解决问题:

using Newtonsoft.Json.Linq;

var Varjson = JObject.Parse(Manjson);

其中 Manjson 是我的 JSON 带有转义字符 ('/') 的字符串。

对象 Varjson 将包含反序列化的 Json 没有转义字符,如下所示:

"{"Apple":"Lion", "Orange":["Tiger","Wolf"], "Mango":"Fox"}"

:)