将定界字符串转换为Expando对象

问题描述 投票:0回答:1

我喜欢这样的字典-

Dictionary<string, Object> dict = new Dictionary<string, Object>();
dict.Add("event.data", "data");
dict.Add("event.Location", LocObj);
dict.Add("event.Details.Cost", CostObj);

我正在尝试将其与现有的json结构合并-

{
   "event" : {
       "name" : "Hello World",
       "tags" : [tags]
    }
    "sponsors" : {
       ...
    }
    "OtherObj" : {
       ...
    }
 }

我正在尝试使用ExpandoObject,然后将其注入到原始json中,就像这样-

 foreach(KeyValuePair<string, Object> kvp in dict) {            

        var newObj= new ExpandoObject() as IDictionary<string, Object>;
        newObj.Add(kvp.Key, value);         

        existingObject.Merge(JObject.FromObject(newObj), new JsonMergeSettings
        {
            MergeArrayHandling = MergeArrayHandling.Union
        });
    }

   Console.WriteLine(JsonConvert.SerializeObject(existingObject));  

但是当它被序列化时,[[event.Location不会显示在现有事件标记中,而是添加了一个名为event.Location的新键。

{ "event" : { "name" : "Hello World", "tags" : [tags] }, "event.Location" : { ... }, <--------------- "event.data": { ... }, <--------------- "event.Details.Cost" : { ... }<--------------- "sponsors" : { ... }, "OtherObj" : { ... } }
如何修复Expando obj创建来解决此问题?
c# .net json json.net expandoobject
1个回答
0
投票
请参见以下程序。这将显示工作合并和中断合并的示例。不同之处在于对象的结构。在一种情况下,“ Event.Location”无效。在另一种情况下,“事件”对象包含一个“位置”,并且它正确地嵌套在JObject的合并操作中。
© www.soinside.com 2019 - 2024. All rights reserved.