c# - 使用 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 结合使用
解决方案是什么:
任何帮助表示赞赏:)
解决方案
我通过将其转换为 JObject 然后按如下方式使用它来解决该问题:
使用 Newtonsoft.Json.Linq;
var Varjson = JObject.Parse(Manjson);
其中 Manjson 是我的带有转义字符 ('/') 的 JSON 字符串。
Object Varjson 将包含不带转义字符的反序列化 Json,如下所示:
"{"Apple":"Lion", "Orange":["Tiger","Wolf"], "Mango":"Fox"}"
:)
推荐阅读
- json - OrientDB索引键值更新查询问题
- flask - 尝试在 Azure 上登录 GoogleOauth,但出现空白页
- ajax - 我想使用 ajax 监控两个文本文件
- asp.net-core - 根据 FileHelpers 示例,如何使用 GetRandomFileName 保存上传的文件以供使用?
- javascript - 无法在应用程序开发工具(javascript)中获取订单按钮的属性值
- python-3.x - 在 python3 中创建十六进制校验和的问题
- mysql - 如何解决 Laravel 6 中的 MariaDB 语法错误?
- hdfs - 调试错误 [Vertica][VJDBC](100172) 一行或多行被服务器拒绝
- python - 有没有办法为子图绘制一条箭头线?
- firebase - 如何使用 Nuxt SSR 设置 Firebase 离线身份验证