10

我有两个JToken's 代表 JSON 对象数组,我想合并它们。JToken有一个方法Concat,但是null当我尝试使用它时它会产生结果。

Action<JToken> Ok = (x) =>
{
    Debug.WriteLine(x);
    /* outputs
    [
      {
        "id": 1,
      },
      {
        "id": 2,
      }
    ]
    */

    x = (x).Concat<JToken>(x) as JToken;
    Debug.WriteLine(x); // null
};

我怎样才能让它工作?

4

3 回答 3

32

JContainer.Merge()与 一起使用MergeArrayHandling.Concat

这从Json.NET 6 Release 4开始可用。因此,如果您的数组在 a 中JContainer(例如 a JObject),这是一个简单而强大的解决方案。

例子:

JObject o1 = JObject.Parse(@"{
  'FirstName': 'John',
  'LastName': 'Smith',
  'Enabled': false,
  'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(@"{
  'Enabled': true,
  'Roles': [ 'Operator', 'Admin' ]
}");

o1.Merge(o2, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Concat });

string json = o1.ToString();
// {
//   "FirstName": "John",
//   "LastName": "Smith",
//   "Enabled": true,
//   "Roles": [
//     "User",
//     "Operator",
//     "Admin"
//   ]
// }
于 2014-12-16T10:24:11.977 回答
9
JToken.FromObject(x.Concat(x))
于 2013-01-02T13:26:15.617 回答
3

我需要同样的,这就是我想出的

https://github.com/MrAntix/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Linq/MergeExtensions.cs

public static void MergeInto(
    this JContainer left, JToken right, MergeOptions options)
{
    foreach (var rightChild in right.Children<JProperty>())
    {
        var rightChildProperty = rightChild;
        var leftPropertyValue = left.SelectToken(rightChildProperty.Name);

        if (leftPropertyValue == null)
        {
            // no matching property, just add 
            left.Add(rightChild);
        }
        else
        {
            var leftProperty = (JProperty) leftPropertyValue.Parent;

            var leftArray = leftPropertyValue as JArray;
            var rightArray = rightChildProperty.Value as JArray;
            if (leftArray != null && rightArray != null)
            {
                switch (options.ArrayHandling)
                {
                    case MergeOptionArrayHandling.Concat:

                        foreach (var rightValue in rightArray)
                        {
                            leftArray.Add(rightValue);
                        }

                        break;
                    case MergeOptionArrayHandling.Overwrite:

                        leftProperty.Value = rightChildProperty.Value;
                        break;
                }
            }

            else
            {
                var leftObject = leftPropertyValue as JObject;
                if (leftObject == null)
                {
                    // replace value
                    leftProperty.Value = rightChildProperty.Value;
                }

                else
                    // recurse object
                    MergeInto(leftObject, rightChildProperty.Value, options);
            }
        }
    }
}
于 2013-06-14T08:06:08.307 回答