首页 > 解决方案 > 使用 ExpandoObject 和 IDictionary 从动态 JSON 中删除转义字符“\”

问题描述

我正在使用 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 表时,它会插入转义字符。

将 Visual Studio 2010 Professional 与 Oracle 11g 和 PL/SQL 11.2 结合使用

解决方案是什么:

任何帮助表示赞赏:)

标签: c#jsonjson.netexpandoobjectidictionary

解决方案


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

使用 Newtonsoft.Json.Linq;

var Varjson = JObject.Parse(Manjson);

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

Object Varjson 将包含不带转义字符的反序列化 Json,如下所示:

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

:)


推荐阅读