从堆栈

时间:2017-06-14 18:57:28

标签: c#

我有一堆包含以下值的字符串:

catalog

catalogtype

catalogtypeoffer

catalogtypeactive

我想获得一个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时,我不会同时将offeractive作为type的子项 - 最后处理的是覆盖另一个。

var jObject = JObject.Parse(BuildJsonStringFromStack(stack));
requestJson.Merge(jObject, new JsonMergeSettings
{
    MergeArrayHandling = MergeArrayHandling.Merge
});

关于如何获得我想要的合并的任何想法?

1 个答案:

答案 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);
        }            
    }