Merge two Json.NET arrays by concatenating contained elements

倾然丶 夕夏残阳落幕 提交于 2019-12-17 07:42:05

问题


I have two JToken's that represent JSON arrays of objects and I would like to merge them. JToken has a method Concat but it produces null as result when I try to use it.

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

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

How can I make it work?


回答1:


Use JContainer.Merge() with MergeArrayHandling.Concat.

This is available starting with Json.NET 6 Release 4. So if your arrays are in a JContainer (e.g. a JObject), this is a simple and robust solution.

Example:

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"
//   ]
// }



回答2:


JToken.FromObject(x.Concat(x))



回答3:


I needed same, here's what I came up with

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


来源:https://stackoverflow.com/questions/14121010/merge-two-json-net-arrays-by-concatenating-contained-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!