-Fixed jsonpath error when parsing a property that follows an escaped property

-Changed reader/writer/token path to escape property names containing special characters
This commit is contained in:
James Newton-King
2014-10-18 15:36:42 +13:00
parent 01f1c5e261
commit 88a29704da
12 changed files with 385 additions and 287 deletions
@@ -33,4 +33,4 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("6.0.0.0")] // [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyVersion("6.0.0.0")] [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.6.17817")] [assembly: AssemblyFileVersion("6.0.6.17818")]
@@ -43,19 +43,19 @@ using System.Linq;
namespace Newtonsoft.Json.Tests.Converters namespace Newtonsoft.Json.Tests.Converters
{ {
[TestFixture] [TestFixture]
public class JsonValueConverterTests : TestFixtureBase public class JsonValueConverterTests : TestFixtureBase
{
public class Computer
{ {
public string Cpu { get; set; } public class Computer
public List<string> Drives { get; set; } {
} public string Cpu { get; set; }
public List<string> Drives { get; set; }
}
[Test] [Test]
public void WriteJson() public void WriteJson()
{ {
JsonObject o = JsonObject.Parse(@"{ JsonObject o = JsonObject.Parse(@"{
""CPU"": ""Intel"", ""CPU"": ""Intel"",
""Drives"": [ ""Drives"": [
""DVD read/writer"", ""DVD read/writer"",
@@ -63,21 +63,21 @@ namespace Newtonsoft.Json.Tests.Converters
] ]
}"); }");
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw); JsonTextWriter writer = new JsonTextWriter(sw);
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
converter.WriteJson(writer, o, null); converter.WriteJson(writer, o, null);
string json = sw.ToString(); string json = sw.ToString();
Assert.AreEqual(@"{""Drives"":[""DVD read/writer"",""500 gigabyte hard drive""],""CPU"":""Intel""}", json); Assert.AreEqual(@"{""Drives"":[""DVD read/writer"",""500 gigabyte hard drive""],""CPU"":""Intel""}", json);
} }
[Test] [Test]
public void ReadJson() public void ReadJson()
{ {
string json = @"{ string json = @"{
""CPU"": ""Intel"", ""CPU"": ""Intel"",
""Drives"": [ ""Drives"": [
""DVD read/writer"", ""DVD read/writer"",
@@ -85,21 +85,21 @@ namespace Newtonsoft.Json.Tests.Converters
] ]
}"; }";
JsonTextReader writer = new JsonTextReader(new StringReader(json)); JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
JsonObject o = (JsonObject)converter.ReadJson(writer, typeof(JsonObject), null, null); JsonObject o = (JsonObject) converter.ReadJson(writer, typeof (JsonObject), null, null);
Assert.AreEqual(2, o.Count); Assert.AreEqual(2, o.Count);
Assert.AreEqual("Intel", o.GetNamedString("CPU")); Assert.AreEqual("Intel", o.GetNamedString("CPU"));
Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString()); Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString());
Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString()); Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString());
} }
[Test] [Test]
public void ReadJsonComments() public void ReadJsonComments()
{ {
string json = @"{/*comment!*/ string json = @"{/*comment!*/
""CPU"": ""Intel"",/*comment!*/ ""CPU"": ""Intel"",/*comment!*/
""Drives"": [/*comment!*/ ""Drives"": [/*comment!*/
""DVD read/writer"", ""DVD read/writer"",
@@ -107,155 +107,156 @@ namespace Newtonsoft.Json.Tests.Converters
]/*comment!*/ ]/*comment!*/
}"; }";
JsonTextReader writer = new JsonTextReader(new StringReader(json)); JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
JsonObject o = (JsonObject)converter.ReadJson(writer, typeof(JsonObject), null, null); JsonObject o = (JsonObject) converter.ReadJson(writer, typeof (JsonObject), null, null);
Assert.AreEqual(2, o.Count); Assert.AreEqual(2, o.Count);
Assert.AreEqual("Intel", o.GetNamedString("CPU")); Assert.AreEqual("Intel", o.GetNamedString("CPU"));
Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString()); Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString());
Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString()); Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString());
} }
[Test] [Test]
public void ReadJsonNullValue() public void ReadJsonNullValue()
{ {
string json = "null"; string json = "null";
JsonTextReader writer = new JsonTextReader(new StringReader(json)); JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
JsonValue v = (JsonValue)converter.ReadJson(writer, typeof(JsonValue), null, null); JsonValue v = (JsonValue) converter.ReadJson(writer, typeof (JsonValue), null, null);
Assert.AreEqual(JsonValueType.Null, v.ValueType); Assert.AreEqual(JsonValueType.Null, v.ValueType);
} }
[Test] [Test]
public void ReadJsonUnsupportedValue() public void ReadJsonUnsupportedValue()
{ {
string json = "undefined"; string json = "undefined";
JsonTextReader writer = new JsonTextReader(new StringReader(json)); JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>(() => ExceptionAssert.Throws<JsonException>(() =>
{ {
converter.ReadJson(writer, typeof(JsonValue), null, null); converter.ReadJson(writer, typeof (JsonValue), null, null);
}, "Unexpected or unsupported token: Undefined. Path '', line 1, position 9."); }, "Unexpected or unsupported token: Undefined. Path '', line 1, position 9.");
} }
[Test] [Test]
public void ReadJsonUnexpectedEndInArray() public void ReadJsonUnexpectedEndInArray()
{ {
string json = "["; string json = "[";
JsonTextReader writer = new JsonTextReader(new StringReader(json)); JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>(() => ExceptionAssert.Throws<JsonException>(() =>
{ {
converter.ReadJson(writer, typeof(JsonValue), null, null); converter.ReadJson(writer, typeof (JsonValue), null, null);
}, "Unexpected end. Path '', line 1, position 1."); }, "Unexpected end. Path '', line 1, position 1.");
} }
[Test] [Test]
public void ReadJsonUnexpectedEndAfterComment() public void ReadJsonUnexpectedEndAfterComment()
{ {
string json = "[/*comment!*/"; string json = "[/*comment!*/";
JsonTextReader writer = new JsonTextReader(new StringReader(json)); JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>(() => ExceptionAssert.Throws<JsonException>(() =>
{ {
converter.ReadJson(writer, typeof(JsonValue), null, null); converter.ReadJson(writer, typeof (JsonValue), null, null);
}, "Unexpected end. Path '', line 1, position 13."); }, "Unexpected end. Path '', line 1, position 13.");
} }
[Test] [Test]
public void ReadJsonUnexpectedEndInObject() public void ReadJsonUnexpectedEndInObject()
{ {
string json = "{'hi':"; string json = "{'hi':";
JsonTextReader writer = new JsonTextReader(new StringReader(json)); JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>(() => ExceptionAssert.Throws<JsonException>(() =>
{ {
converter.ReadJson(writer, typeof(JsonValue), null, null); converter.ReadJson(writer, typeof (JsonValue), null, null);
}, "Unexpected end. Path 'hi', line 1, position 6."); }, "Unexpected end. Path 'hi', line 1, position 6.");
} }
[Test] [Test]
public void ReadJsonBadJsonType() public void ReadJsonBadJsonType()
{ {
string json = "null"; string json = "null";
JsonTextReader writer = new JsonTextReader(new StringReader(json)); JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter(); JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>(() => ExceptionAssert.Throws<JsonException>(() =>
{ {
converter.ReadJson(writer, typeof(JsonObject), null, null); converter.ReadJson(writer, typeof (JsonObject), null, null);
}, "Could not convert 'Windows.Data.Json.JsonValue' to 'Windows.Data.Json.JsonObject'. Path '', line 1, position 4."); },
} "Could not convert 'Windows.Data.Json.JsonValue' to 'Windows.Data.Json.JsonObject'. Path '', line 1, position 4.");
}
[Test] [Test]
public void JsonConvertDeserialize() public void JsonConvertDeserialize()
{ {
string json = @"[ string json = @"[
""DVD read/writer"", ""DVD read/writer"",
""500 gigabyte hard drive"" ""500 gigabyte hard drive""
]"; ]";
JsonArray a = JsonConvert.DeserializeObject<JsonArray>(json); JsonArray a = JsonConvert.DeserializeObject<JsonArray>(json);
Assert.AreEqual(2, a.Count); Assert.AreEqual(2, a.Count);
Assert.AreEqual("DVD read/writer", a[0].GetString()); Assert.AreEqual("DVD read/writer", a[0].GetString());
Assert.AreEqual("500 gigabyte hard drive", a[1].GetString()); Assert.AreEqual("500 gigabyte hard drive", a[1].GetString());
} }
[Test] [Test]
public void JsonConvertSerialize() public void JsonConvertSerialize()
{ {
JsonArray a = JsonArray.Parse(@"[ JsonArray a = JsonArray.Parse(@"[
""DVD read/writer"", ""DVD read/writer"",
""500 gigabyte hard drive"" ""500 gigabyte hard drive""
]"); ]");
string json = JsonConvert.SerializeObject(a, Formatting.Indented); string json = JsonConvert.SerializeObject(a, Formatting.Indented);
Assert.AreEqual(@"[ Assert.AreEqual(@"[
""DVD read/writer"", ""DVD read/writer"",
""500 gigabyte hard drive"" ""500 gigabyte hard drive""
]", json); ]", json);
} }
[Test] [Test]
public void SerializeDouble() public void SerializeDouble()
{ {
JsonObject o = new JsonObject(); JsonObject o = new JsonObject();
o["zero"] = JsonValue.CreateNumberValue(0); o["zero"] = JsonValue.CreateNumberValue(0);
o["int"] = JsonValue.CreateNumberValue(1); o["int"] = JsonValue.CreateNumberValue(1);
o["smallfraction"] = JsonValue.CreateNumberValue(3.0000000000000009); o["smallfraction"] = JsonValue.CreateNumberValue(3.0000000000000009);
o["double"] = JsonValue.CreateNumberValue(1.1); o["double"] = JsonValue.CreateNumberValue(1.1);
o["probablyint"] = JsonValue.CreateNumberValue(1.0); o["probablyint"] = JsonValue.CreateNumberValue(1.0);
o["Epsilon"] = JsonValue.CreateNumberValue(double.Epsilon); o["Epsilon"] = JsonValue.CreateNumberValue(double.Epsilon);
o["MinValue"] = JsonValue.CreateNumberValue(double.MinValue); o["MinValue"] = JsonValue.CreateNumberValue(double.MinValue);
o["MaxValue"] = JsonValue.CreateNumberValue(double.MaxValue); o["MaxValue"] = JsonValue.CreateNumberValue(double.MaxValue);
o["NaN"] = JsonValue.CreateNumberValue(double.NaN); o["NaN"] = JsonValue.CreateNumberValue(double.NaN);
o["NegativeInfinity"] = JsonValue.CreateNumberValue(double.NegativeInfinity); o["NegativeInfinity"] = JsonValue.CreateNumberValue(double.NegativeInfinity);
o["PositiveInfinity"] = JsonValue.CreateNumberValue(double.PositiveInfinity); o["PositiveInfinity"] = JsonValue.CreateNumberValue(double.PositiveInfinity);
string json = JsonConvert.SerializeObject(o, Formatting.Indented); string json = JsonConvert.SerializeObject(o, Formatting.Indented);
Assert.AreEqual(@"{ Assert.AreEqual(@"{
""PositiveInfinity"": ""Infinity"", ""PositiveInfinity"": ""Infinity"",
""NegativeInfinity"": ""-Infinity"", ""NegativeInfinity"": ""-Infinity"",
""MinValue"": -1.7976931348623157E+308, ""MinValue"": -1.7976931348623157E+308,
@@ -268,12 +269,12 @@ namespace Newtonsoft.Json.Tests.Converters
""smallfraction"": 3.0000000000000009, ""smallfraction"": 3.0000000000000009,
""probablyint"": 1 ""probablyint"": 1
}", json); }", json);
} }
[Test] [Test]
public void DeserializePerformance() public void DeserializePerformance()
{ {
string json = @"{ string json = @"{
""CPU"": ""Intel"", ""CPU"": ""Intel"",
""Drives"": [ ""Drives"": [
""DVD read/writer"", ""DVD read/writer"",
@@ -281,46 +282,46 @@ namespace Newtonsoft.Json.Tests.Converters
] ]
}"; }";
Stopwatch timer = new Stopwatch(); Stopwatch timer = new Stopwatch();
timer.Start(); timer.Start();
for (int i = 0; i < 100000; i++) for (int i = 0; i < 100000; i++)
{ {
JsonObject o = JsonObject.Parse(json); JsonObject o = JsonObject.Parse(json);
} }
timer.Stop(); timer.Stop();
string winrt = timer.Elapsed.TotalSeconds.ToString(); string winrt = timer.Elapsed.TotalSeconds.ToString();
timer = new Stopwatch(); timer = new Stopwatch();
timer.Start(); timer.Start();
for (int i = 0; i < 100000; i++) for (int i = 0; i < 100000; i++)
{ {
JObject o = JObject.Parse(json); JObject o = JObject.Parse(json);
} }
timer.Stop(); timer.Stop();
string linq = timer.Elapsed.TotalSeconds.ToString(); string linq = timer.Elapsed.TotalSeconds.ToString();
// warm up // warm up
JsonConvert.DeserializeObject<Computer>(json); JsonConvert.DeserializeObject<Computer>(json);
timer = new Stopwatch(); timer = new Stopwatch();
timer.Start(); timer.Start();
for (int i = 0; i < 100000; i++) for (int i = 0; i < 100000; i++)
{ {
Computer o = JsonConvert.DeserializeObject<Computer>(json); Computer o = JsonConvert.DeserializeObject<Computer>(json);
} }
timer.Stop(); timer.Stop();
string jsonnet = timer.Elapsed.TotalSeconds.ToString(); string jsonnet = timer.Elapsed.TotalSeconds.ToString();
throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq)); Debug.WriteLine("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq);
} }
[Test] [Test]
public void SerializePerformance() public void SerializePerformance()
{ {
string json = @"{ string json = @"{
""CPU"": ""Intel"", ""CPU"": ""Intel"",
""Drives"": [ ""Drives"": [
""DVD read/writer"", ""DVD read/writer"",
@@ -328,46 +329,46 @@ namespace Newtonsoft.Json.Tests.Converters
] ]
}"; }";
JsonObject o = JsonObject.Parse(json); JsonObject o = JsonObject.Parse(json);
JObject o1 = JObject.Parse(json); JObject o1 = JObject.Parse(json);
Computer o2 = JsonConvert.DeserializeObject<Computer>(json); Computer o2 = JsonConvert.DeserializeObject<Computer>(json);
Stopwatch timer = new Stopwatch(); Stopwatch timer = new Stopwatch();
timer.Start(); timer.Start();
for (int i = 0; i < 100000; i++) for (int i = 0; i < 100000; i++)
{ {
o.Stringify(); o.Stringify();
} }
timer.Stop(); timer.Stop();
string winrt = timer.Elapsed.TotalSeconds.ToString(); string winrt = timer.Elapsed.TotalSeconds.ToString();
timer.Start(); timer.Start();
for (int i = 0; i < 100000; i++) for (int i = 0; i < 100000; i++)
{ {
o1.ToString(Formatting.None); o1.ToString(Formatting.None);
} }
timer.Stop(); timer.Stop();
string linq = timer.Elapsed.TotalSeconds.ToString(); string linq = timer.Elapsed.TotalSeconds.ToString();
timer = new Stopwatch(); timer = new Stopwatch();
timer.Start(); timer.Start();
for (int i = 0; i < 100000; i++) for (int i = 0; i < 100000; i++)
{ {
JsonConvert.SerializeObject(o); JsonConvert.SerializeObject(o);
} }
timer.Stop(); timer.Stop();
string jsonnet = timer.Elapsed.TotalSeconds.ToString(); string jsonnet = timer.Elapsed.TotalSeconds.ToString();
throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq)); Debug.WriteLine("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq);
} }
[Test] [Test]
public void ParseJson() public void ParseJson()
{ {
string json = @"{ string json = @"{
""channel"": { ""channel"": {
""title"": ""James Newton-King"", ""title"": ""James Newton-King"",
""link"": ""http://james.newtonking.com"", ""link"": ""http://james.newtonking.com"",
@@ -386,67 +387,74 @@ namespace Newtonsoft.Json.Tests.Converters
} }
}"; }";
// Windows.Data.Json // Windows.Data.Json
// ----------------- // -----------------
JsonObject jsonObject = JsonObject.Parse(json); JsonObject jsonObject = JsonObject.Parse(json);
string itemTitle1 = jsonObject["channel"].GetObject()["item"].GetArray()[0].GetObject()["title"].GetString(); string itemTitle1 = jsonObject["channel"].GetObject()["item"].GetArray()[0].GetObject()["title"].GetString();
// LINQ to JSON // LINQ to JSON
// ------------ // ------------
JObject jObject = JObject.Parse(json); JObject jObject = JObject.Parse(json);
string itemTitle2 = (string)jObject["channel"]["item"][0]["title"]; string itemTitle2 = (string) jObject["channel"]["item"][0]["title"];
} }
[Test] [Test]
public void CreateJson() public void CreateJson()
{
// Windows.Data.Json
// -----------------
JsonObject jsonObject = new JsonObject
{ {
{"CPU", JsonValue.CreateStringValue("Intel")}, // Windows.Data.Json
{"Drives", new JsonArray { // -----------------
JsonValue.CreateStringValue("DVD read/writer"), JsonObject jsonObject = new JsonObject
JsonValue.CreateStringValue("500 gigabyte hard drive") {
} {"CPU", JsonValue.CreateStringValue("Intel")},
} {
}; "Drives", new JsonArray
string json1 = jsonObject.Stringify(); {
JsonValue.CreateStringValue("DVD read/writer"),
JsonValue.CreateStringValue("500 gigabyte hard drive")
}
}
};
string json1 = jsonObject.Stringify();
// LINQ to JSON // LINQ to JSON
// ------------ // ------------
JObject jObject = new JObject JObject jObject = new JObject
{
{"CPU", "Intel"},
{
"Drives", new JArray
{
"DVD read/writer",
"500 gigabyte hard drive"
}
}
};
string json2 = jObject.ToString();
}
[Test]
public void Converting()
{ {
{"CPU", "Intel"}, JsonObject jsonObject = new JsonObject
{"Drives", new JArray { {
"DVD read/writer", {"CPU", JsonValue.CreateStringValue("Intel")},
"500 gigabyte hard drive" {
} "Drives", new JsonArray
} {
}; JsonValue.CreateStringValue("DVD read/writer"),
string json2 = jObject.ToString(); JsonValue.CreateStringValue("500 gigabyte hard drive")
}
}
};
// convert Windows.Data.Json to LINQ to JSON
JObject o = JObject.FromObject(jsonObject);
// convert LINQ to JSON to Windows.Data.Json
JArray a = (JArray) o["Drives"];
JsonArray jsonArray = a.ToObject<JsonArray>();
}
} }
[Test]
public void Converting()
{
JsonObject jsonObject = new JsonObject
{
{"CPU", JsonValue.CreateStringValue("Intel")},
{"Drives", new JsonArray {
JsonValue.CreateStringValue("DVD read/writer"),
JsonValue.CreateStringValue("500 gigabyte hard drive")
}
}
};
// convert Windows.Data.Json to LINQ to JSON
JObject o = JObject.FromObject(jsonObject);
// convert LINQ to JSON to Windows.Data.Json
JArray a = (JArray)o["Drives"];
JsonArray jsonArray = a.ToObject<JsonArray>();
}
}
} }
#endif #endif
@@ -3151,6 +3151,32 @@ null//comment
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
} }
[Test]
public void EscapedPathInExceptionMessage()
{
string json = @"{
""frameworks"": {
""aspnetcore50"": {
""dependencies"": {
""System.Xml.ReaderWriter"": {
""source"": !!! !!!
}
}
}
}
}";
ExceptionAssert.Throws<JsonReaderException>(
() =>
{
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
}
},
"Unexpected character encountered while parsing value: !. Path 'frameworks.aspnetcore50.dependencies.['System.Xml.ReaderWriter'].source', line 6, position 21.");
}
} }
public class ToggleReaderError : TextReader public class ToggleReaderError : TextReader
@@ -643,5 +643,18 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{ {
ExceptionAssert.Throws<JsonException>(() => { new JPath("[1]Blah"); }, "Unexpected character following indexer: B"); ExceptionAssert.Throws<JsonException>(() => { new JPath("[1]Blah"); }, "Unexpected character following indexer: B");
} }
[Test]
public void PropertyFollowingEscapedPropertyName()
{
JPath path = new JPath("frameworks.aspnetcore50.dependencies.['System.Xml.ReaderWriter'].source");
Assert.AreEqual(5, path.Filters.Count);
Assert.AreEqual("frameworks", ((FieldFilter)path.Filters[0]).Name);
Assert.AreEqual("aspnetcore50", ((FieldFilter)path.Filters[1]).Name);
Assert.AreEqual("dependencies", ((FieldFilter)path.Filters[2]).Name);
Assert.AreEqual("System.Xml.ReaderWriter", ((FieldFilter)path.Filters[3]).Name);
Assert.AreEqual("source", ((FieldFilter)path.Filters[4]).Name);
}
} }
} }
@@ -184,6 +184,55 @@ undefined
Assert.AreEqual("person.$id", idProperty.Path); Assert.AreEqual("person.$id", idProperty.Path);
} }
[Test]
public void EscapedPath()
{
string json = @"{
""frameworks"": {
""aspnetcore50"": {
""dependencies"": {
""System.Xml.ReaderWriter"": {
""source"": ""NuGet""
}
}
}
}
}";
JObject o = JObject.Parse(json);
JToken v1 = o["frameworks"]["aspnetcore50"]["dependencies"]["System.Xml.ReaderWriter"]["source"];
Console.WriteLine(v1.Path);
JToken v2 = o.SelectToken(v1.Path);
Assert.AreEqual(v1, v2);
}
[Test]
public void EscapedPathTests()
{
EscapedPathAssert("this has spaces", "['this has spaces']");
EscapedPathAssert("(RoundBraces)", "['(RoundBraces)']");
EscapedPathAssert("[SquareBraces]", "['[SquareBraces]']");
EscapedPathAssert("this.has.dots", "['this.has.dots']");
}
private void EscapedPathAssert(string propertyName, string expectedPath)
{
int v1 = int.MaxValue;
JValue value = new JValue(v1);
JObject o = new JObject(new JProperty(propertyName, value));
Assert.AreEqual(expectedPath, value.Path);
JValue selectedValue = (JValue)o.SelectToken(value.Path);
Assert.AreEqual(value, selectedValue);
}
[Test] [Test]
public void ForEach() public void ForEach()
{ {
@@ -16,6 +16,7 @@
<ProjectTypeGuids>{BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <ProjectTypeGuids>{BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<PackageCertificateKeyFile>Newtonsoft.Json.Tests.WinRT_TemporaryKey.pfx</PackageCertificateKeyFile> <PackageCertificateKeyFile>Newtonsoft.Json.Tests.WinRT_TemporaryKey.pfx</PackageCertificateKeyFile>
<PackageCertificateThumbprint>3116117C65F73A227A0BDC35F584F04145BA4BB7</PackageCertificateThumbprint> <PackageCertificateThumbprint>3116117C65F73A227A0BDC35F584F04145BA4BB7</PackageCertificateThumbprint>
<AppxAutoIncrementPackageRevision>False</AppxAutoIncrementPackageRevision>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@@ -381,6 +382,7 @@
<ItemGroup> <ItemGroup>
<Reference Include="System.Collections.Immutable"> <Reference Include="System.Collections.Immutable">
<HintPath>..\packages\Microsoft.Bcl.Immutable.1.1.20-beta\lib\portable-net45+win8\System.Collections.Immutable.dll</HintPath> <HintPath>..\packages\Microsoft.Bcl.Immutable.1.1.20-beta\lib\portable-net45+win8\System.Collections.Immutable.dll</HintPath>
<Private>True</Private>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '12.0' "> <PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '12.0' ">
@@ -74,4 +74,4 @@ using System.Security;
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")] [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.6.17817")] [assembly: AssemblyFileVersion("6.0.6.17818")]
@@ -3215,7 +3215,7 @@ Path '', line 1, position 1.");
} }
catch (JsonSerializationException ex) catch (JsonSerializationException ex)
{ {
Assert.IsTrue(ex.Message.StartsWith("Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Path 'Newtonsoft.Json.Tests.TestObjects.Person'")); Assert.IsTrue(ex.Message.StartsWith("Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Path '['Newtonsoft.Json.Tests.TestObjects.Person']'"));
} }
} }
+14 -1
View File
@@ -41,6 +41,8 @@ namespace Newtonsoft.Json
internal struct JsonPosition internal struct JsonPosition
{ {
private static readonly char[] SpecialCharacters = {'.', ' ', '[', ']', '(', ')'};
internal JsonContainerType Type; internal JsonContainerType Type;
internal int Position; internal int Position;
internal string PropertyName; internal string PropertyName;
@@ -61,7 +63,18 @@ namespace Newtonsoft.Json
case JsonContainerType.Object: case JsonContainerType.Object:
if (sb.Length > 0) if (sb.Length > 0)
sb.Append('.'); sb.Append('.');
sb.Append(PropertyName);
string propertyName = PropertyName;
if (propertyName.IndexOfAny(SpecialCharacters) != -1)
{
sb.Append(@"['");
sb.Append(propertyName);
sb.Append(@"']");
}
else
{
sb.Append(propertyName);
}
break; break;
case JsonContainerType.Array: case JsonContainerType.Array:
case JsonContainerType.Constructor: case JsonContainerType.Constructor:
+4 -10
View File
@@ -188,7 +188,7 @@ namespace Newtonsoft.Json.Linq
IList<JToken> ancestors = Ancestors().Reverse().ToList(); IList<JToken> ancestors = Ancestors().Reverse().ToList();
ancestors.Add(this); ancestors.Add(this);
StringBuilder sb = new StringBuilder(); IList<JsonPosition> positions = new List<JsonPosition>();
for (int i = 0; i < ancestors.Count; i++) for (int i = 0; i < ancestors.Count; i++)
{ {
JToken current = ancestors[i]; JToken current = ancestors[i];
@@ -204,25 +204,19 @@ namespace Newtonsoft.Json.Linq
{ {
case JTokenType.Property: case JTokenType.Property:
JProperty property = (JProperty)current; JProperty property = (JProperty)current;
positions.Add(new JsonPosition(JsonContainerType.Object) { PropertyName = property.Name });
if (sb.Length > 0)
sb.Append('.');
sb.Append(property.Name);
break; break;
case JTokenType.Array: case JTokenType.Array:
case JTokenType.Constructor: case JTokenType.Constructor:
int index = ((IList<JToken>)current).IndexOf(next); int index = ((IList<JToken>)current).IndexOf(next);
sb.Append('['); positions.Add(new JsonPosition(JsonContainerType.Array) { Position = index });
sb.Append(index);
sb.Append(']');
break; break;
} }
} }
} }
return sb.ToString(); return JsonPosition.BuildPath(positions);
} }
} }
@@ -609,24 +609,17 @@ namespace Newtonsoft.Json.Linq.JsonPath
private PathFilter ParseQuotedField(char indexerCloseChar) private PathFilter ParseQuotedField(char indexerCloseChar)
{ {
//_currentIndex++;
//int start = _currentIndex;
List<string> fields = null; List<string> fields = null;
while (_currentIndex < _expression.Length) while (_currentIndex < _expression.Length)
{ {
string field = ReadQuotedString(); string field = ReadQuotedString();
//_currentIndex++;
//EnsureLength("Path ended with open indexer.");
EatWhitespace(); EatWhitespace();
EnsureLength("Path ended with open indexer."); EnsureLength("Path ended with open indexer.");
if (_expression[_currentIndex] == indexerCloseChar) if (_expression[_currentIndex] == indexerCloseChar)
{ {
_currentIndex++;
if (fields != null) if (fields != null)
{ {
fields.Add(field); fields.Add(field);
@@ -91,5 +91,5 @@ using System.Security;
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")] [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.6.17817")] [assembly: AssemblyFileVersion("6.0.6.17818")]
[assembly: CLSCompliant(true)] [assembly: CLSCompliant(true)]