-Documentation

This commit is contained in:
James Newton-King
2012-08-12 23:04:36 +12:00
parent 693d1d5d3e
commit 44c2773263
12 changed files with 345 additions and 83 deletions
+50
View File
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<topic id="CreatingLINQtoJSON" revisionNumber="1">
<developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink">
<introduction>
<para>As well as parsing JSON from existing JSON strings, LINQ to JSON objects can be created from scratch to create new JSON structures.</para>
</introduction>
<section>
<title>Manually Creating JSON</title>
<content>
<para>Setting values and creating objects and arrays one at a time gives you
total control but it is more verbose than other options.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateNormal" title="Creating JSON" />
</content>
</section>
<section>
<title>Creating JSON with LINQ</title>
<content>
<para>Declaratively creating JSON objects using LINQ is a fast way to create JSON from collections of values.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateDeclaratively" title="Creating JSON Declaratively" />
</content>
</section>
<section>
<title>Creating JSON from an object</title>
<content>
<para>The last option is to create a JSON object from a non-JSON type using the
<codeEntityReference>Overload:Newtonsoft.Json.Linq.JObject.FromObject</codeEntityReference>
method. Internally FromObject will use the JsonSerializer to serialize the object to LINQ to JSON objects instead of text.</para>
<para>The example below is creating a JSON object from an anonymous object but any
.NET type can be used with FromObject to create JSON.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateFromObject" title="Creating JSON from an Object" />
</content>
</section>
<relatedTopics>
<externalLink>
<linkText>LINQ to JSON</linkText>
<linkUri>LINQtoJSON.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink>
<codeEntityReference>Overload:Newtonsoft.Json.Linq.JObject.FromObject</codeEntityReference>
</relatedTopics>
</developerConceptualDocument>
</topic>
+46 -74
View File
@@ -2,86 +2,58 @@
<topic id="LINQtoJSON" revisionNumber="1">
<developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink">
<introduction>
<para>LINQ to JSON is a programming API for working with JSON objects.
<para>LINQ to JSON is an API for working with JSON objects.
The API has been designed with LINQ in mind to enable to quick querying
and creation of JSON objects. LINQ to JSON sits under the
<codeEntityReference>N:Newtonsoft.Json.Linq</codeEntityReference>
namespace.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonBasic" title="Using LINQ for JSON" />
</introduction>
<section>
<title>Reading JSON</title>
<content>
<para>JSON values can be read from a string use the
<codeEntityReference>M:Newtonsoft.Json.Linq.JToken.Parse(System.String)</codeEntityReference>
method.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" />
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" />
</content>
</section>
<section>
<title>Creating JSON</title>
<content>
<!-- Uncomment this to create a sub-section outline
<autoOutline /> -->
<para>There are a number of different options when it comes to creating
JSON using LINQ to JSON.</para>
<para>The first option is to set values one at a time. You
have total control but it is more verbose than other options.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateNormal" title="Creating JSON" />
<para>Another option is to create JSON objects declaratively using LINQ.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateDeclaratively" title="Creating JSON Declaratively" />
<para>Finally you can create a JSON object from a non-JSON type using the
<codeEntityReference>Overload:Newtonsoft.Json.Linq.JObject.FromObject</codeEntityReference>
method. The example below is creating a JSON object from an anonymous object but any
.NET type can be used with FromObject to create JSON.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateFromObject" title="Creating JSON from an Object" />
</content>
</section>
<section>
<title>Querying JSON</title>
<content>
<!-- Uncomment this to create a sub-section outline
<autoOutline /> -->
<para>The properties and methods that are the most useful when querying JSON
objects are
<codeEntityReference>M:Newtonsoft.Json.Linq.JToken.Children</codeEntityReference>
and
<codeEntityReference>P:Newtonsoft.Json.Linq.JToken.Item(System.Object)</codeEntityReference>.</para>
<para>Children returns all the children of that object. If it is a
JObject it will return a collection of properties to work with and if
it is a JArray you will get a collection of the array's values.</para>
<para>The index property is used to get a specific child, either by
index position for JSON arrays or property name for JSON objects.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonQuerying" title="Querying JSON" />
<para>LINQ to JSON can also be used to manually convert from JSON to a .NET object.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonDeserializeObject" title="Deserializing Using LINQ Objects" />
<para>Manually serializing and deserializing between .NET objects is most useful when
working with JSON that doesn't closely match your .NET objects.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonDeserializeExample" title="Deserializing Using LINQ Example" />
</content>
</section>
<section>
<title>Topics</title>
<content>
<para>Select a topic below for more information:</para>
<list class="bullet">
<listItem>
<para>
<externalLink>
<linkText>Parsing JSON</linkText>
<linkUri>ParsingLINQtoJSON.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink>
</para>
</listItem>
<listItem>
<para>
<externalLink>
<linkText>Creating JSON</linkText>
<linkUri>CreatingLINQtoJSON.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink>
</para>
</listItem>
<listItem>
<para>
<externalLink>
<linkText>Querying JSON with LINQ</linkText>
<linkUri>QueryingLINQtoJSON.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink>
</para>
</listItem>
<listItem>
<para>
<externalLink>
<linkText>Querying JSON with SelectToken</linkText>
<linkUri>SelectToken.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink>
</para>
</listItem>
</list>
</content>
</section>
<relatedTopics>
<externalLink>
<linkText>Querying LINQ to JSON with SelectToken</linkText>
<linkUri>SelectToken.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink>
<codeEntityReference>T:Newtonsoft.Json.Linq.JObject</codeEntityReference>
<codeEntityReference>T:Newtonsoft.Json.Linq.JArray</codeEntityReference>
<codeEntityReference>T:Newtonsoft.Json.Linq.JValue</codeEntityReference>
+37
View File
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<topic id="ParsingLINQtoJSON" revisionNumber="1">
<developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink">
<introduction>
<para>LINQ to JSON has methods available for parsing JSON from a string or loading JSON directly from a file.</para>
</introduction>
<section>
<title>Parsing JSON text</title>
<content>
<para>JSON values can be read from a string using
<codeEntityReference>M:Newtonsoft.Json.Linq.JToken.Parse(System.String)</codeEntityReference>.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from text" />
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from text" />
</content>
</section>
<section>
<title>Loading JSON from a file</title>
<content>
<para>JSON can also be loaded directly from a file using <codeEntityReference>M:Newtonsoft.Json.Linq.JToken.ReadFrom(Newtonsoft.Json.JsonReader)</codeEntityReference>.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonReadObject" title="Reading JSON from a file" />
</content>
</section>
<relatedTopics>
<externalLink>
<linkText>LINQ to JSON</linkText>
<linkUri>LINQtoJSON.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink>
<codeEntityReference>M:Newtonsoft.Json.Linq.JToken.Parse(System.String)</codeEntityReference>
<codeEntityReference>M:Newtonsoft.Json.Linq.JToken.ReadFrom(Newtonsoft.Json.JsonReader)</codeEntityReference>
</relatedTopics>
</developerConceptualDocument>
</topic>
+60
View File
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<topic id="QueryingLINQtoJSON" revisionNumber="1">
<developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink">
<introduction>
<para>LINQ to JSON provides a number of methods for getting data from its objects. The index methods on JObject/JArray let you quickly get data by its property name
on an object or index in a collection, while <codeEntityReference>M:Newtonsoft.Json.Linq.JToken.Children</codeEntityReference> lets you get ranges
of data as <codeInline>IEnumerable&lt;JToken&gt;</codeInline> to then query using LINQ.</para>
</introduction>
<section>
<title>Getting values by Property Name or Collection Index</title>
<content>
<!-- Uncomment this to create a sub-section outline
<autoOutline /> -->
<para>The simplest way to get a value from LINQ to JSON is to use the
<codeEntityReference>P:Newtonsoft.Json.Linq.JToken.Item(System.Object)</codeEntityReference> index on
JObject/JArray and then cast the returned <codeEntityReference>T:Newtonsoft.Json.Linq.JValue</codeEntityReference> to the type you want.
</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonSimpleQuerying" title="Getting JSON Values" />
</content>
</section>
<section>
<title>Querying with LINQ</title>
<content>
<para>JObject/JArray can also be queried using LINQ. <codeEntityReference>M:Newtonsoft.Json.Linq.JToken.Children</codeEntityReference>
returns the children values of a JObject/JArray
as an <codeInline>IEnumerable&lt;JToken&gt;</codeInline> that can then be queried with the standard Where/OrderBy/Select LINQ operators.</para>
<alert class="note">
<para><codeEntityReference>M:Newtonsoft.Json.Linq.JToken.Children</codeEntityReference> returns all the children of a token. If it is a
JObject it will return a collection of properties to work with and if
it is a JArray you will get a collection of the array's values.</para>
</alert>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonQuerying" title="Querying JSON" />
<para>LINQ to JSON can also be used to manually convert JSON to a .NET object.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonDeserializeObject" title="Deserializing Using LINQ Objects" />
<para>Manually serializing and deserializing between .NET objects is useful when you are
working with JSON that doesn't closely match your .NET objects.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonDeserializeExample" title="Deserializing Using LINQ Example" />
</content>
</section>
<relatedTopics>
<externalLink>
<linkText>LINQ to JSON</linkText>
<linkUri>LINQtoJSON.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink>
<codeEntityReference>P:Newtonsoft.Json.Linq.JToken.Item(System.Object)</codeEntityReference>
<codeEntityReference>M:Newtonsoft.Json.Linq.JToken.Children</codeEntityReference>
</relatedTopics>
</developerConceptualDocument>
</topic>
+6 -3
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Topics>
<Topic id="Introduction" visible="True" isDefault="true" />
<Topic id="SerializingJSON" visible="True" isExpanded="true" title="Serializing and Deserializing JSON">
<Topic id="SerializingJSON" visible="True" title="Serializing and Deserializing JSON">
<Topic id="SerializationSettings" visible="True" title="Serialization Settings" />
<Topic id="SerializationGuide" visible="True" title="Serialization Guide" />
<Topic id="SerializationAttributes" visible="True" title="Serialization Attributes" />
@@ -16,8 +16,11 @@
<Topic id="SerializingJSONFragments" visible="True" title="Serializing Partial JSON Fragments" />
</Topic>
<Topic id="LINQtoJSON" visible="True" isExpanded="true" title="LINQ to JSON">
<Topic id="SelectToken" visible="True" title="Querying LINQ to JSON with SelectToken" />
<Topic id="ParsingLINQtoJSON" visible="True" isSelected="true" title="Parsing JSON" />
<Topic id="CreatingLINQtoJSON" visible="True" title="Creating JSON" />
<Topic id="QueryingLINQtoJSON" visible="True" title="Querying JSON with LINQ" />
<Topic id="SelectToken" visible="True" title="Querying JSON with SelectToken" />
</Topic>
<Topic id="ReadingWritingJSON" visible="True" isSelected="true" title="Basic Reading and Writing JSON" />
<Topic id="ReadingWritingJSON" visible="True" title="Basic Reading and Writing JSON" />
<Topic id="ConvertingJSONandXML" visible="True" title="Converting between JSON and XML" />
</Topics>
+3
View File
@@ -140,6 +140,9 @@
<None Include="CustomCreationConverter.aml" />
<None Include="ContractResolver.aml" />
<None Include="ConvertingJSONandXML.aml" />
<None Include="CreatingLINQtoJSON.aml" />
<None Include="ParsingLINQtoJSON.aml" />
<None Include="QueryingLINQtoJSON.aml" />
<None Include="ReadingWritingJSON.aml" />
<None Include="SelectToken.aml" />
<None Include="LINQtoJSON.aml" />
@@ -46,11 +46,35 @@ using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using File = System.IO.File;
namespace Newtonsoft.Json.Tests.Documentation
{
public class LinqToJsonTests
{
public void LinqToJsonBasic()
{
#region LinqToJsonBasic
JObject o = JObject.Parse(@"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
#endregion
}
public void LinqToJsonCreateNormal()
{
#region LinqToJsonCreateNormal
@@ -194,6 +218,73 @@ namespace Newtonsoft.Json.Tests.Documentation
#endregion
}
public static class File
{
public static StreamReader OpenText(string path)
{
return null;
}
}
public void LinqToJsonReadObject()
{
#region LinqToJsonReadObject
using (StreamReader reader = File.OpenText(@"c:\person.json"))
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
// do stuff
}
#endregion
}
public void LinqToJsonSimpleQuerying()
{
#region LinqToJsonSimpleQuerying
string json = @"{
'channel': {
'title': 'James Newton-King',
'link': 'http://james.newtonking.com',
'description': 'James Newton-King's blog.',
'item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Annoucing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'LINQ'
]
}
]
}
}";
JObject rss = JObject.Parse(json);
string rssTitle = (string)rss["channel"]["title"];
// James Newton-King
string itemTitle = (string)rss["channel"]["item"][0]["title"];
// Json.NET 1.3 + New license + Now on CodePlex
JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
// ["Json.NET", "CodePlex"]
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
// Json.NET
// CodePlex
#endregion
}
public void LinqToJsonQuerying()
{
JObject rss = new JObject();
@@ -882,6 +882,30 @@ namespace Newtonsoft.Json.Tests.Documentation
// Url = http://www.imdb.com/name/nm0385296/
#endregion
}
public void SerializeMultidimensionalArrayExample()
{
string[,] famousCouples = new string[,]
{
{"Adam", "Eve"},
{"Bonnie", "Clyde"},
{"Donald", "Daisy"},
{"Han", "Leia"}
};
string json = JsonConvert.SerializeObject(famousCouples, Formatting.Indented);
// [
// ["Adam", "Eve"],
// ["Bonnie", "Clyde"],
// ["Donald", "Daisy"],
// ["Han", "Leia"]
// ]
string[,] deserialized = JsonConvert.DeserializeObject<string[,]>(json);
Console.WriteLine(deserialized[3, 0] + ", " + deserialized[3, 1]);
// Han, Leia
}
}
}
#endif
+24 -3
View File
@@ -65,8 +65,8 @@ namespace Newtonsoft.Json.Tests
[TestFixture]
public class PerformanceTests : TestFixtureBase
{
private const int Iterations = 100;
//private const int Iterations = 5000;
//private const int Iterations = 100;
private const int Iterations = 5000;
#region Data
@@ -768,6 +768,27 @@ namespace Newtonsoft.Json.Tests
BenchmarkSerializeMethod(SerializeMethod.JsonNet, s);
}
[Test]
public void ParseJObject()
{
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
JObject o = JObject.Parse(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
}
timer.Stop();
string linq = timer.Elapsed.TotalSeconds.ToString();
Console.WriteLine(linq);
}
[Test]
public void JObjectToString()
{
@@ -778,7 +799,7 @@ namespace Newtonsoft.Json.Tests
for (int i = 0; i < Iterations; i++)
{
test["dummy"] = new JValue(i);
Encoding.UTF8.GetBytes(test.ToString(Formatting.None));
test.ToString(Formatting.None);
}
return null;
}, "JObject.ToString");
@@ -72,5 +72,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.8.15205")]
[assembly: AssemblyFileVersion("4.5.8.15212")]
#endif
+2 -1
View File
@@ -58,7 +58,6 @@ namespace Newtonsoft.Json.Linq
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
internal ListChangedEventHandler _listChanged;
internal AddingNewEventHandler _addingNew;
internal NotifyCollectionChangedEventHandler _collectionChanged;
/// <summary>
/// Occurs when the list changes or an item in the list changes.
@@ -79,6 +78,8 @@ namespace Newtonsoft.Json.Linq
}
#endif
#if SILVERLIGHT || !(NET20 || NET35 || PORTABLE)
internal NotifyCollectionChangedEventHandler _collectionChanged;
/// <summary>
/// Occurs when the items list of the collection has changed, or the collection is reset.
/// </summary>
@@ -91,7 +91,7 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.8.15205")]
[assembly: AssemblyFileVersion("4.5.8.15212")]
#endif
[assembly: CLSCompliant(true)]