From e5eaa1499072c1220e6ef1769a391717e2547c00 Mon Sep 17 00:00:00 2001 From: JamesNK Date: Fri, 27 Feb 2009 07:02:36 +0000 Subject: [PATCH] -Added AddAfterSelf, AddBeforeSelf to JToken --- Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs | 58 +++++++++++++++++++ Src/Newtonsoft.Json/Linq/JToken.cs | 20 +++++++ 2 files changed, 78 insertions(+) diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs index 776c34e3..b4e4c218 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs @@ -516,5 +516,63 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(@"[""2009-02-15T00:00:00.0000000Z""]", json); } + + [Test] + public void AddAfterSelf() + { + JArray a = + new JArray( + 5, + new JArray(1), + new JArray(1, 2), + new JArray(1, 2, 3) + ); + + a[1].AddAfterSelf("pie"); + + Assert.AreEqual(5, (int)a[0]); + Assert.AreEqual(1, a[1].Count()); + Assert.AreEqual("pie", (string)a[2]); + Assert.AreEqual(5, a.Count()); + + a[4].AddAfterSelf("lastpie"); + + Assert.AreEqual("lastpie", (string)a[5]); + Assert.AreEqual("lastpie", (string)a.Last); + } + + [Test] + public void AddBeforeSelf() + { + JArray a = + new JArray( + 5, + new JArray(1), + new JArray(1, 2), + new JArray(1, 2, 3) + ); + + a[1].AddBeforeSelf("pie"); + + Assert.AreEqual(5, (int)a[0]); + Assert.AreEqual("pie", (string)a[1]); + Assert.AreEqual(a, a[1].Parent); + Assert.AreEqual(a[2], a[1].Next); + Assert.AreEqual(5, a.Count()); + + a[0].AddBeforeSelf("firstpie"); + + Assert.AreEqual("firstpie", (string)a[0]); + Assert.AreEqual(5, (int)a[1]); + Assert.AreEqual("pie", (string)a[2]); + Assert.AreEqual(a, a[0].Parent); + Assert.AreEqual(a[1], a[0].Next); + Assert.AreEqual(6, a.Count()); + + a.Last.AddBeforeSelf("secondlastpie"); + + Assert.AreEqual("secondlastpie", (string)a[5]); + Assert.AreEqual(7, a.Count()); + } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 1b88c067..24a6096f 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -164,6 +164,26 @@ namespace Newtonsoft.Json.Linq { } + public void AddAfterSelf(object content) + { + if (_parent == null) + throw new InvalidOperationException("The parent is missing."); + + _parent.AddInternal((Next == null), this, content); + } + + public void AddBeforeSelf(object content) + { + if (_parent == null) + throw new InvalidOperationException("The parent is missing."); + + JToken previous = Previous; + if (previous == null) + previous = _parent.Last; + + _parent.AddInternal(false, previous, content); + } + /// /// Returns a collection of the ancestor tokens of this token. ///