从迭代路径构建JObject

时间:2018-11-05 17:45:15

标签: json.net

我需要动态构建一个对象,然后可以将其序列化为JSON字符串。本质上,我正在使用两个新字典来创建新对象。

var myValues= new Dictionary<string, object>
{
    { "Value1", "Foo" },
    { "Value2", "Bar" }
};
var mappedValues = new Dictionary<string, string>
{
    { "Value1", "Some:Path" },
    { "Value2", "Some:OtherPath }
};

在我遍历的过程中,我需要能够构建Json Object,以便最终得到类似的东西:

{
  "Some": {
    "Path": "Foo",
    "OtherPath": "Bar"
  }
}

从我所看到的,Newtonsoft.Json并没有内置具体方法,但是我希望有人可能对我如何能够最有效地实现目标有所了解。

1 个答案:

答案 0 :(得分:0)

目前似乎没有任何方法可以创建内置在Newtonsoft.Json中的元素...但是我最终想出了以下可行的解决方案

private JObject DoFoo()
{
    var jObject = new JObject();
    foreach(var mapping in mappedValues)
    {
        var queue = new Queue<string>(mapping.Value.Split(':');
        var value = myValues[mapping.Key];
        SetValueWithPath(jObject, queue, value);
    }

    return jObject;
}

private void SetValueWithPath(JObject parent, Queue<string> path, object content)
{
    var currentNode = path?.FirstOrDefault();
    if (string.IsNullOrEmpty(currentNode)) return;

    if (path.Count == 1)
    {
        parent[currentNode] = JToken.FromObject(content);
        return;
    }
    else if (!parent.ContainsKey(currentNode))
    {
        parent[currentNode] = new JObject();
    }

    path.Dequeue();
    SetValueWithPath(parent[currentNode] as JObject, path, content);
}
相关问题