我有一堆包含以下值的字符串:
catalog
catalog
,type
catalog
,type
,offer
catalog
,type
,active
我想获得一个JSON结构,如:
{ catalog:
{ type:
{
offer: '',
active: ''
}
},
}
我试过这个:
private static string BuildJsonStringFromStack(Stack<string> stack)
{
if (stack.Count == 1)
{
return $"{{{stack.Pop()}: {{}}}}";
}
var json = new StringBuilder("{");
var depth = stack.Count;
while (stack.Any())
{
if (stack.Count == 1)
{
json.Append($"{stack.Pop()}: ''");
json.Append(new String('}', depth));
}
else
{
json.Append($"{stack.Pop()}: {{");
}
}
return json.ToString();
}
这会给我一些字符串:
{ catalog:
{ type:
{
offer: ''
}
}
}
{ catalog:
{ type:
{
active: ''
}
}
}
但是,当我尝试将字符串合并到JObject
时,我不会同时将offer
和active
作为type
的子项 - 最后处理的是覆盖另一个。
var jObject = JObject.Parse(BuildJsonStringFromStack(stack));
requestJson.Merge(jObject, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Merge
});
关于如何获得我想要的合并的任何想法?
答案 0 :(得分:2)
感谢Gusman的评论,这很简单:
dynamic expando = new ExpandoObject();
foreach (var stack in stacks)
{
CreateExpando(expando, stack);
}
return JsonConvert.SerializeObject(expando);
哪个电话:
private static void CreateExpando(ExpandoObject expando, Stack<string> stack)
{
var expandoDict = expando as IDictionary<string, object>;
var item = stack.Pop();
ExpandoObject expandoRef = new ExpandoObject();
if (!expandoDict.Keys.Contains(item)) {
expandoDict.Add(item, expandoRef);
}
else {
expandoRef = expandoDict[item] as ExpandoObject;
}
if (stack.Any())
{
CreateExpando(expandoRef, stack);
}
}