2
// Copyright (c) 2007 James Newton-King
4
// Permission is hereby granted, free of charge, to any person
5
// obtaining a copy of this software and associated documentation
6
// files (the "Software"), to deal in the Software without
7
// restriction, including without limitation the rights to use,
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
9
// copies of the Software, and to permit persons to whom the
10
// Software is furnished to do so, subject to the following
13
// The above copyright notice and this permission notice shall be
14
// included in all copies or substantial portions of the Software.
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
// OTHER DEALINGS IN THE SOFTWARE.
27
using System.Collections.Generic;
30
using Newtonsoft.Json.Utilities;
31
using System.Diagnostics;
32
using System.Globalization;
33
using System.Collections;
34
using System.ComponentModel;
36
namespace Newtonsoft.Json.Linq
39
/// Represents an abstract JSON token.
41
public abstract class JToken : IJEnumerable<JToken>, IJsonLineInfo
43
private JContainer _parent;
44
internal JToken _next;
45
private static JTokenEqualityComparer _equalityComparer;
47
private int? _lineNumber;
48
private int? _linePosition;
51
/// Gets a comparer that can compare two tokens for value equality.
53
/// <value>A <see cref="JTokenEqualityComparer"/> that can compare two nodes for value equality.</value>
54
public static JTokenEqualityComparer EqualityComparer
58
if (_equalityComparer == null)
59
_equalityComparer = new JTokenEqualityComparer();
61
return _equalityComparer;
66
/// Gets or sets the parent.
68
/// <value>The parent.</value>
69
public JContainer Parent
72
get { return _parent; }
73
internal set { _parent = value; }
77
/// Gets the root <see cref="JToken"/> of this <see cref="JToken"/>.
79
/// <value>The root <see cref="JToken"/> of this <see cref="JToken"/>.</value>
84
JContainer parent = Parent;
88
while (parent.Parent != null)
90
parent = parent.Parent;
97
internal abstract JToken CloneToken();
98
internal abstract bool DeepEquals(JToken node);
101
/// Gets the node type for this <see cref="JToken"/>.
103
/// <value>The type.</value>
104
public abstract JTokenType Type { get; }
107
/// Gets a value indicating whether this token has childen tokens.
110
/// <c>true</c> if this token has child values; otherwise, <c>false</c>.
112
public abstract bool HasValues { get; }
115
/// Compares the values of two tokens, including the values of all descendant tokens.
117
/// <param name="t1">The first <see cref="JToken"/> to compare.</param>
118
/// <param name="t2">The second <see cref="JToken"/> to compare.</param>
119
/// <returns>true if the tokens are equal; otherwise false.</returns>
120
public static bool DeepEquals(JToken t1, JToken t2)
122
return (t1 == t2 || (t1 != null && t2 != null && t1.DeepEquals(t2)));
126
/// Gets the next sibling token of this node.
128
/// <value>The <see cref="JToken"/> that contains the next sibling token.</value>
133
if (_parent != null && _next != _parent.First)
138
internal set { _next = value; }
142
/// Gets the previous sibling token of this node.
144
/// <value>The <see cref="JToken"/> that contains the previous sibling token.</value>
145
public JToken Previous
152
JToken parentNext = _parent.Content._next;
153
JToken parentNextBefore = null;
154
while (parentNext != this)
156
parentNextBefore = parentNext;
157
parentNext = parentNext.Next;
159
return parentNextBefore;
168
/// Adds the specified content immediately after this token.
170
/// <param name="content">A content object that contains simple content or a collection of content objects to be added after this token.</param>
171
public void AddAfterSelf(object content)
174
throw new InvalidOperationException("The parent is missing.");
176
_parent.AddInternal((Next == null), this, content);
180
/// Adds the specified content immediately before this token.
182
/// <param name="content">A content object that contains simple content or a collection of content objects to be added before this token.</param>
183
public void AddBeforeSelf(object content)
186
throw new InvalidOperationException("The parent is missing.");
188
JToken previous = Previous;
189
if (previous == null)
190
previous = _parent.Last;
192
_parent.AddInternal(false, previous, content);
196
/// Returns a collection of the ancestor tokens of this token.
198
/// <returns>A collection of the ancestor tokens of this token.</returns>
199
public IEnumerable<JToken> Ancestors()
201
for (JToken parent = Parent; parent != null; parent = parent.Parent)
208
/// Returns a collection of the sibling tokens after this token, in document order.
210
/// <returns>A collection of the sibling tokens after this tokens, in document order.</returns>
211
public IEnumerable<JToken> AfterSelf()
216
for (JToken o = Next; o != null; o = o.Next)
221
/// Returns a collection of the sibling tokens before this token, in document order.
223
/// <returns>A collection of the sibling tokens before this token, in document order.</returns>
224
public IEnumerable<JToken> BeforeSelf()
226
for (JToken o = Parent.First; o != this; o = o.Next)
231
/// Gets the <see cref="JToken"/> with the specified key.
233
/// <value>The <see cref="JToken"/> with the specified key.</value>
234
public virtual JToken this[object key]
236
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); }
237
set { throw new InvalidOperationException("Cannot set child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); }
241
/// Gets the <see cref="JToken"/> with the specified key converted to the specified type.
243
/// <typeparam name="T">The type to convert the token to.</typeparam>
244
/// <param name="key">The token key.</param>
245
/// <returns>The converted token value.</returns>
246
public virtual T Value<T>(object key)
248
JToken token = this[key];
250
return Extensions.Convert<JToken, T>(token);
254
/// Get the first child token of this token.
256
/// <value>A <see cref="JToken"/> containing the first child token of the <see cref="JToken"/>.</value>
257
public virtual JToken First
259
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); }
263
/// Get the last child token of this token.
265
/// <value>A <see cref="JToken"/> containing the last child token of the <see cref="JToken"/>.</value>
266
public virtual JToken Last
268
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); }
272
/// Returns a collection of the child tokens of this token, in document order.
274
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> containing the child tokens of this <see cref="JToken"/>, in document order.</returns>
275
public virtual JEnumerable<JToken> Children()
277
throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
281
/// Returns a collection of the child tokens of this token, in document order, filtered by the specified type.
283
/// <typeparam name="T">The type to filter the child tokens on.</typeparam>
284
/// <returns>A <see cref="JEnumerable{T}"/> containing the child tokens of this <see cref="JToken"/>, in document order.</returns>
285
public JEnumerable<T> Children<T>() where T : JToken
287
return new JEnumerable<T>(Children().OfType<T>());
291
/// Returns a collection of the child values of this token, in document order.
293
/// <typeparam name="T">The type to convert the values to.</typeparam>
294
/// <returns>A <see cref="IEnumerable{T}"/> containing the child values of this <see cref="JToken"/>, in document order.</returns>
295
public virtual IEnumerable<T> Values<T>()
297
throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
301
/// Removes this token from its parent.
306
throw new InvalidOperationException("The parent is missing.");
308
_parent.RemoveItem(this);
312
/// Replaces this token with the specified token.
314
/// <param name="value">The value.</param>
315
public void Replace(JToken value)
318
throw new InvalidOperationException("The parent is missing.");
320
_parent.ReplaceItem(this, value);
324
/// Writes this token to a <see cref="JsonWriter"/>.
326
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
327
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
328
public abstract void WriteTo(JsonWriter writer, params JsonConverter[] converters);
331
/// Returns the indented JSON for this token.
334
/// The indented JSON for this token.
336
public override string ToString()
338
return ToString(Formatting.Indented);
342
/// Returns the JSON for this token using the given formatting and converters.
344
/// <param name="formatting">Indicates how the output is formatted.</param>
345
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
346
/// <returns>The JSON for this token using the given formatting and converters.</returns>
347
public string ToString(Formatting formatting, params JsonConverter[] converters)
349
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
351
JsonTextWriter jw = new JsonTextWriter(sw);
352
jw.Formatting = formatting;
354
WriteTo(jw, converters);
356
return sw.ToString();
360
private static JValue EnsureValue(JToken value)
363
throw new ArgumentNullException("value");
365
if (value is JProperty)
366
value = ((JProperty)value).Value;
368
JValue v = value as JValue;
373
private static string GetType(JToken token)
375
ValidationUtils.ArgumentNotNull(token, "token");
377
if (token is JProperty)
378
token = ((JProperty)token).Value;
380
return token.Type.ToString();
383
private static bool IsNullable(JToken o)
385
return (o.Type == JTokenType.Undefined || o.Type == JTokenType.Null);
388
private static bool ValidateFloat(JToken o, bool nullable)
390
return (o.Type == JTokenType.Float || o.Type == JTokenType.Integer || (nullable && IsNullable(o)));
393
private static bool ValidateInteger(JToken o, bool nullable)
395
return (o.Type == JTokenType.Integer || (nullable && IsNullable(o)));
398
private static bool ValidateDate(JToken o, bool nullable)
400
return (o.Type == JTokenType.Date || (nullable && IsNullable(o)));
403
private static bool ValidateBoolean(JToken o, bool nullable)
405
return (o.Type == JTokenType.Boolean || (nullable && IsNullable(o)));
408
private static bool ValidateString(JToken o)
410
return (o.Type == JTokenType.String || o.Type == JTokenType.Comment || o.Type == JTokenType.Raw || IsNullable(o));
413
private static bool ValidateBytes(JToken o)
415
return (o.Type == JTokenType.Bytes || IsNullable(o));
418
#region Cast from operators
420
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Boolean"/>.
422
/// <param name="value">The value.</param>
423
/// <returns>The result of the conversion.</returns>
424
public static explicit operator bool(JToken value)
426
JValue v = EnsureValue(value);
427
if (v == null || !ValidateBoolean(v, false))
428
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
430
return (bool)v.Value;
433
#if !PocketPC && !NET20
435
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.DateTimeOffset"/>.
437
/// <param name="value">The value.</param>
438
/// <returns>The result of the conversion.</returns>
439
public static explicit operator DateTimeOffset(JToken value)
441
JValue v = EnsureValue(value);
442
if (v == null || !ValidateDate(v, false))
443
throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
445
return (DateTimeOffset)v.Value;
450
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Boolean}"/>.
452
/// <param name="value">The value.</param>
453
/// <returns>The result of the conversion.</returns>
454
public static explicit operator bool?(JToken value)
459
JValue v = EnsureValue(value);
460
if (v == null || !ValidateBoolean(v, true))
461
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
463
return (bool?)v.Value;
467
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Int64"/>.
469
/// <param name="value">The value.</param>
470
/// <returns>The result of the conversion.</returns>
471
public static explicit operator long(JToken value)
473
JValue v = EnsureValue(value);
474
if (v == null || !ValidateInteger(v, false))
475
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
477
return (long)v.Value;
481
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{DateTime}"/>.
483
/// <param name="value">The value.</param>
484
/// <returns>The result of the conversion.</returns>
485
public static explicit operator DateTime?(JToken value)
490
JValue v = EnsureValue(value);
491
if (v == null || !ValidateDate(v, true))
492
throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
494
return (DateTime?)v.Value;
497
#if !PocketPC && !NET20
499
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{DateTimeOffset}"/>.
501
/// <param name="value">The value.</param>
502
/// <returns>The result of the conversion.</returns>
503
public static explicit operator DateTimeOffset?(JToken value)
508
JValue v = EnsureValue(value);
509
if (v == null || !ValidateDate(v, true))
510
throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
512
return (DateTimeOffset?)v.Value;
517
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Decimal}"/>.
519
/// <param name="value">The value.</param>
520
/// <returns>The result of the conversion.</returns>
521
public static explicit operator decimal?(JToken value)
526
JValue v = EnsureValue(value);
527
if (v == null || !ValidateFloat(v, true))
528
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
530
return (v.Value != null) ? (decimal?)Convert.ToDecimal(v.Value, CultureInfo.InvariantCulture) : null;
534
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Double}"/>.
536
/// <param name="value">The value.</param>
537
/// <returns>The result of the conversion.</returns>
538
public static explicit operator double?(JToken value)
543
JValue v = EnsureValue(value);
544
if (v == null || !ValidateFloat(v, true))
545
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
547
return (double?)v.Value;
551
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Int32"/>.
553
/// <param name="value">The value.</param>
554
/// <returns>The result of the conversion.</returns>
555
public static explicit operator int(JToken value)
557
JValue v = EnsureValue(value);
558
if (v == null || !ValidateInteger(v, false))
559
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
561
return Convert.ToInt32(v.Value, CultureInfo.InvariantCulture);
565
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Int32}"/>.
567
/// <param name="value">The value.</param>
568
/// <returns>The result of the conversion.</returns>
569
public static explicit operator int?(JToken value)
574
JValue v = EnsureValue(value);
575
if (v == null || !ValidateInteger(v, true))
576
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
578
return (v.Value != null) ? (int?)Convert.ToInt32(v.Value, CultureInfo.InvariantCulture) : null;
582
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.DateTime"/>.
584
/// <param name="value">The value.</param>
585
/// <returns>The result of the conversion.</returns>
586
public static explicit operator DateTime(JToken value)
588
JValue v = EnsureValue(value);
589
if (v == null || !ValidateDate(v, false))
590
throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
592
return (DateTime)v.Value;
596
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Int64}"/>.
598
/// <param name="value">The value.</param>
599
/// <returns>The result of the conversion.</returns>
600
public static explicit operator long?(JToken value)
605
JValue v = EnsureValue(value);
606
if (v == null || !ValidateInteger(v, true))
607
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
609
return (long?)v.Value;
613
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Single}"/>.
615
/// <param name="value">The value.</param>
616
/// <returns>The result of the conversion.</returns>
617
public static explicit operator float?(JToken value)
622
JValue v = EnsureValue(value);
623
if (v == null || !ValidateFloat(v, true))
624
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
626
return (v.Value != null) ? (float?)Convert.ToSingle(v.Value, CultureInfo.InvariantCulture) : null;
630
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Decimal"/>.
632
/// <param name="value">The value.</param>
633
/// <returns>The result of the conversion.</returns>
634
public static explicit operator decimal(JToken value)
636
JValue v = EnsureValue(value);
637
if (v == null || !ValidateFloat(v, false))
638
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
640
return Convert.ToDecimal(v.Value, CultureInfo.InvariantCulture);
644
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{UInt32}"/>.
646
/// <param name="value">The value.</param>
647
/// <returns>The result of the conversion.</returns>
648
[CLSCompliant(false)]
649
public static explicit operator uint?(JToken value)
654
JValue v = EnsureValue(value);
655
if (v == null || !ValidateInteger(v, true))
656
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
658
return (uint?)v.Value;
662
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{UInt64}"/>.
664
/// <param name="value">The value.</param>
665
/// <returns>The result of the conversion.</returns>
666
[CLSCompliant(false)]
667
public static explicit operator ulong?(JToken value)
672
JValue v = EnsureValue(value);
673
if (v == null || !ValidateInteger(v, true))
674
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
676
return (ulong?)v.Value;
680
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Double"/>.
682
/// <param name="value">The value.</param>
683
/// <returns>The result of the conversion.</returns>
684
public static explicit operator double(JToken value)
686
JValue v = EnsureValue(value);
687
if (v == null || !ValidateFloat(v, false))
688
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
690
return (double)v.Value;
694
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Single"/>.
696
/// <param name="value">The value.</param>
697
/// <returns>The result of the conversion.</returns>
698
public static explicit operator float(JToken value)
700
JValue v = EnsureValue(value);
701
if (v == null || !ValidateFloat(v, false))
702
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
704
return Convert.ToSingle(v.Value, CultureInfo.InvariantCulture);
708
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.String"/>.
710
/// <param name="value">The value.</param>
711
/// <returns>The result of the conversion.</returns>
712
public static explicit operator string(JToken value)
717
JValue v = EnsureValue(value);
718
if (v == null || !ValidateString(v))
719
throw new ArgumentException("Can not convert {0} to String.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
721
return (string)v.Value;
725
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.UInt32"/>.
727
/// <param name="value">The value.</param>
728
/// <returns>The result of the conversion.</returns>
729
[CLSCompliant(false)]
730
public static explicit operator uint(JToken value)
732
JValue v = EnsureValue(value);
733
if (v == null || !ValidateInteger(v, false))
734
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
736
return Convert.ToUInt32(v.Value, CultureInfo.InvariantCulture);
740
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.UInt64"/>.
742
/// <param name="value">The value.</param>
743
/// <returns>The result of the conversion.</returns>
744
[CLSCompliant(false)]
745
public static explicit operator ulong(JToken value)
747
JValue v = EnsureValue(value);
748
if (v == null || !ValidateInteger(v, false))
749
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
751
return Convert.ToUInt64(v.Value, CultureInfo.InvariantCulture);
755
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="T:System.Byte[]"/>.
757
/// <param name="value">The value.</param>
758
/// <returns>The result of the conversion.</returns>
759
public static explicit operator byte[](JToken value)
761
JValue v = EnsureValue(value);
762
if (v == null || !ValidateBytes(v))
763
throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
765
return (byte[])v.Value;
769
#region Cast to operators
771
/// Performs an implicit conversion from <see cref="Boolean"/> to <see cref="JToken"/>.
773
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
774
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
775
public static implicit operator JToken(bool value)
777
return new JValue(value);
780
#if !PocketPC && !NET20
782
/// Performs an implicit conversion from <see cref="DateTimeOffset"/> to <see cref="JToken"/>.
784
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
785
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
786
public static implicit operator JToken(DateTimeOffset value)
788
return new JValue(value);
793
/// Performs an implicit conversion from <see cref="Nullable{Boolean}"/> to <see cref="JToken"/>.
795
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
796
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
797
public static implicit operator JToken(bool? value)
799
return new JValue(value);
803
/// Performs an implicit conversion from <see cref="Nullable{Int64}"/> to <see cref="JToken"/>.
805
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
806
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
807
public static implicit operator JToken(long value)
809
return new JValue(value);
813
/// Performs an implicit conversion from <see cref="Nullable{DateTime}"/> to <see cref="JToken"/>.
815
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
816
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
817
public static implicit operator JToken(DateTime? value)
819
return new JValue(value);
822
#if !PocketPC && !NET20
824
/// Performs an implicit conversion from <see cref="Nullable{DateTimeOffset}"/> to <see cref="JToken"/>.
826
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
827
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
828
public static implicit operator JToken(DateTimeOffset? value)
830
return new JValue(value);
835
/// Performs an implicit conversion from <see cref="Nullable{Decimal}"/> to <see cref="JToken"/>.
837
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
838
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
839
public static implicit operator JToken(decimal? value)
841
return new JValue(value);
845
/// Performs an implicit conversion from <see cref="Nullable{Double}"/> to <see cref="JToken"/>.
847
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
848
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
849
public static implicit operator JToken(double? value)
851
return new JValue(value);
855
/// Performs an implicit conversion from <see cref="UInt16"/> to <see cref="JToken"/>.
857
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
858
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
859
[CLSCompliant(false)]
860
public static implicit operator JToken(ushort value)
862
return new JValue(value);
866
/// Performs an implicit conversion from <see cref="Int32"/> to <see cref="JToken"/>.
868
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
869
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
870
public static implicit operator JToken(int value)
872
return new JValue(value);
876
/// Performs an implicit conversion from <see cref="Nullable{Int32}"/> to <see cref="JToken"/>.
878
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
879
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
880
public static implicit operator JToken(int? value)
882
return new JValue(value);
886
/// Performs an implicit conversion from <see cref="DateTime"/> to <see cref="JToken"/>.
888
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
889
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
890
public static implicit operator JToken(DateTime value)
892
return new JValue(value);
896
/// Performs an implicit conversion from <see cref="Nullable{Int64}"/> to <see cref="JToken"/>.
898
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
899
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
900
public static implicit operator JToken(long? value)
902
return new JValue(value);
906
/// Performs an implicit conversion from <see cref="Nullable{Single}"/> to <see cref="JToken"/>.
908
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
909
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
910
public static implicit operator JToken(float? value)
912
return new JValue(value);
916
/// Performs an implicit conversion from <see cref="Decimal"/> to <see cref="JToken"/>.
918
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
919
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
920
public static implicit operator JToken(decimal value)
922
return new JValue(value);
926
/// Performs an implicit conversion from <see cref="Nullable{UInt16}"/> to <see cref="JToken"/>.
928
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
929
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
930
[CLSCompliant(false)]
931
public static implicit operator JToken(ushort? value)
933
return new JValue(value);
937
/// Performs an implicit conversion from <see cref="Nullable{UInt32}"/> to <see cref="JToken"/>.
939
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
940
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
941
[CLSCompliant(false)]
942
public static implicit operator JToken(uint? value)
944
return new JValue(value);
948
/// Performs an implicit conversion from <see cref="Nullable{UInt64}"/> to <see cref="JToken"/>.
950
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
951
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
952
[CLSCompliant(false)]
953
public static implicit operator JToken(ulong? value)
955
return new JValue(value);
959
/// Performs an implicit conversion from <see cref="Double"/> to <see cref="JToken"/>.
961
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
962
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
963
public static implicit operator JToken(double value)
965
return new JValue(value);
969
/// Performs an implicit conversion from <see cref="Single"/> to <see cref="JToken"/>.
971
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
972
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
973
public static implicit operator JToken(float value)
975
return new JValue(value);
979
/// Performs an implicit conversion from <see cref="String"/> to <see cref="JToken"/>.
981
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
982
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
983
public static implicit operator JToken(string value)
985
return new JValue(value);
989
/// Performs an implicit conversion from <see cref="UInt32"/> to <see cref="JToken"/>.
991
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
992
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
993
[CLSCompliant(false)]
994
public static implicit operator JToken(uint value)
996
return new JValue(value);
1000
/// Performs an implicit conversion from <see cref="UInt64"/> to <see cref="JToken"/>.
1002
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1003
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1004
[CLSCompliant(false)]
1005
public static implicit operator JToken(ulong value)
1007
return new JValue(value);
1011
/// Performs an implicit conversion from <see cref="T:System.Byte[]"/> to <see cref="Newtonsoft.Json.Linq.JToken"/>.
1013
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1014
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1015
public static implicit operator JToken(byte[] value)
1017
return new JValue(value);
1021
IEnumerator IEnumerable.GetEnumerator()
1023
return ((IEnumerable<JToken>)this).GetEnumerator();
1026
IEnumerator<JToken> IEnumerable<JToken>.GetEnumerator()
1028
return Children().GetEnumerator();
1031
internal abstract int GetDeepHashCode();
1033
IJEnumerable<JToken> IJEnumerable<JToken>.this[object key]
1035
get { return this[key]; }
1039
/// Creates an <see cref="JsonReader"/> for this token.
1041
/// <returns>An <see cref="JsonReader"/> that can be used to read this token and its descendants.</returns>
1042
public JsonReader CreateReader()
1044
return new JTokenReader(this);
1047
internal static JToken FromObjectInternal(object o, JsonSerializer jsonSerializer)
1049
ValidationUtils.ArgumentNotNull(o, "o");
1050
ValidationUtils.ArgumentNotNull(jsonSerializer, "jsonSerializer");
1053
using (JTokenWriter jsonWriter = new JTokenWriter())
1055
jsonSerializer.Serialize(jsonWriter, o);
1056
token = jsonWriter.Token;
1063
/// Creates a <see cref="JToken"/> from an object.
1065
/// <param name="o">The object that will be used to create <see cref="JToken"/>.</param>
1066
/// <returns>A <see cref="JToken"/> with the value of the specified object</returns>
1067
public static JToken FromObject(object o)
1069
return FromObjectInternal(o, new JsonSerializer());
1073
/// Creates a <see cref="JToken"/> from an object using the specified <see cref="JsonSerializer"/>.
1075
/// <param name="o">The object that will be used to create <see cref="JToken"/>.</param>
1076
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when reading the object.</param>
1077
/// <returns>A <see cref="JToken"/> with the value of the specified object</returns>
1078
public static JToken FromObject(object o, JsonSerializer jsonSerializer)
1080
return FromObjectInternal(o, jsonSerializer);
1084
/// Creates a <see cref="JToken"/> from a <see cref="JsonReader"/>.
1086
/// <param name="reader">An <see cref="JsonReader"/> positioned at the token to read into this <see cref="JToken"/>.</param>
1088
/// An <see cref="JToken"/> that contains the token and its descendant tokens
1089
/// that were read from the reader. The runtime type of the token is determined
1090
/// by the token type of the first token encountered in the reader.
1092
public static JToken ReadFrom(JsonReader reader)
1094
ValidationUtils.ArgumentNotNull(reader, "reader");
1096
if (reader.TokenType == JsonToken.None)
1099
throw new Exception("Error reading JToken from JsonReader.");
1102
if (reader.TokenType == JsonToken.StartObject)
1103
return JObject.Load(reader);
1105
if (reader.TokenType == JsonToken.StartArray)
1106
return JArray.Load(reader);
1108
if (reader.TokenType == JsonToken.PropertyName)
1109
return JProperty.Load(reader);
1111
if (reader.TokenType == JsonToken.StartConstructor)
1112
return JConstructor.Load(reader);
1114
// hack. change to look at TokenType rather than using value
1115
if (!JsonReader.IsStartToken(reader.TokenType))
1116
return new JValue(reader.Value);
1118
// TODO: loading constructor and parameters?
1119
throw new Exception("Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
1122
internal void SetLineInfo(IJsonLineInfo lineInfo)
1124
if (lineInfo == null || !lineInfo.HasLineInfo())
1127
SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition);
1130
internal void SetLineInfo(int lineNumber, int linePosition)
1132
_lineNumber = lineNumber;
1133
_linePosition = linePosition;
1136
bool IJsonLineInfo.HasLineInfo()
1138
return (_lineNumber != null && _linePosition != null);
1141
int IJsonLineInfo.LineNumber
1143
get { return _lineNumber ?? 0; }
1146
int IJsonLineInfo.LinePosition
1148
get { return _linePosition ?? 0; }
1152
/// Selects the token that matches the object path.
1154
/// <param name="path">
1155
/// The object path from the current <see cref="JToken"/> to the <see cref="JToken"/>
1156
/// to be returned. This must be a string of property names or array indexes separated
1157
/// by periods, such as <code>Tables[0].DefaultView[0].Price</code> in C# or
1158
/// <code>Tables(0).DefaultView(0).Price</code> in Visual Basic.
1160
/// <returns>The <see cref="JToken"/> that matches the object path or a null reference if no matching token is found.</returns>
1161
public JToken SelectToken(string path)
1163
return SelectToken(path, false);
1167
/// Selects the token that matches the object path.
1169
/// <param name="path">
1170
/// The object path from the current <see cref="JToken"/> to the <see cref="JToken"/>
1171
/// to be returned. This must be a string of property names or array indexes separated
1172
/// by periods, such as <code>Tables[0].DefaultView[0].Price</code> in C# or
1173
/// <code>Tables(0).DefaultView(0).Price</code> in Visual Basic.
1175
/// <param name="errorWhenNoMatch">A flag to indicate whether an error should be thrown if no token is found.</param>
1176
/// <returns>The <see cref="JToken"/> that matches the object path.</returns>
1177
public JToken SelectToken(string path, bool errorWhenNoMatch)
1179
JPath p = new JPath(path);
1180
return p.Evaluate(this, errorWhenNoMatch);
2
// Copyright (c) 2007 James Newton-King
4
// Permission is hereby granted, free of charge, to any person
5
// obtaining a copy of this software and associated documentation
6
// files (the "Software"), to deal in the Software without
7
// restriction, including without limitation the rights to use,
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
9
// copies of the Software, and to permit persons to whom the
10
// Software is furnished to do so, subject to the following
13
// The above copyright notice and this permission notice shall be
14
// included in all copies or substantial portions of the Software.
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
// OTHER DEALINGS IN THE SOFTWARE.
27
using System.Collections.Generic;
28
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
30
using System.Linq.Expressions;
33
using Newtonsoft.Json.Utilities;
34
using System.Diagnostics;
35
using System.Globalization;
36
using System.Collections;
38
using Newtonsoft.Json.Utilities.LinqBridge;
43
namespace Newtonsoft.Json.Linq
46
/// Represents an abstract JSON token.
48
public abstract class JToken : IJEnumerable<JToken>, IJsonLineInfo
49
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
52
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
53
, IDynamicMetaObjectProvider
56
private JContainer _parent;
57
private JToken _previous;
59
private static JTokenEqualityComparer _equalityComparer;
61
private int? _lineNumber;
62
private int? _linePosition;
65
/// Gets a comparer that can compare two tokens for value equality.
67
/// <value>A <see cref="JTokenEqualityComparer"/> that can compare two nodes for value equality.</value>
68
public static JTokenEqualityComparer EqualityComparer
72
if (_equalityComparer == null)
73
_equalityComparer = new JTokenEqualityComparer();
75
return _equalityComparer;
80
/// Gets or sets the parent.
82
/// <value>The parent.</value>
83
public JContainer Parent
86
get { return _parent; }
87
internal set { _parent = value; }
91
/// Gets the root <see cref="JToken"/> of this <see cref="JToken"/>.
93
/// <value>The root <see cref="JToken"/> of this <see cref="JToken"/>.</value>
98
JContainer parent = Parent;
102
while (parent.Parent != null)
104
parent = parent.Parent;
111
internal abstract JToken CloneToken();
112
internal abstract bool DeepEquals(JToken node);
115
/// Gets the node type for this <see cref="JToken"/>.
117
/// <value>The type.</value>
118
public abstract JTokenType Type { get; }
121
/// Gets a value indicating whether this token has childen tokens.
124
/// <c>true</c> if this token has child values; otherwise, <c>false</c>.
126
public abstract bool HasValues { get; }
129
/// Compares the values of two tokens, including the values of all descendant tokens.
131
/// <param name="t1">The first <see cref="JToken"/> to compare.</param>
132
/// <param name="t2">The second <see cref="JToken"/> to compare.</param>
133
/// <returns>true if the tokens are equal; otherwise false.</returns>
134
public static bool DeepEquals(JToken t1, JToken t2)
136
return (t1 == t2 || (t1 != null && t2 != null && t1.DeepEquals(t2)));
140
/// Gets the next sibling token of this node.
142
/// <value>The <see cref="JToken"/> that contains the next sibling token.</value>
145
get { return _next; }
146
internal set { _next = value; }
150
/// Gets the previous sibling token of this node.
152
/// <value>The <see cref="JToken"/> that contains the previous sibling token.</value>
153
public JToken Previous
155
get { return _previous; }
156
internal set { _previous = value; }
164
/// Adds the specified content immediately after this token.
166
/// <param name="content">A content object that contains simple content or a collection of content objects to be added after this token.</param>
167
public void AddAfterSelf(object content)
170
throw new InvalidOperationException("The parent is missing.");
172
int index = _parent.IndexOfItem(this);
173
_parent.AddInternal(index + 1, content, false);
177
/// Adds the specified content immediately before this token.
179
/// <param name="content">A content object that contains simple content or a collection of content objects to be added before this token.</param>
180
public void AddBeforeSelf(object content)
183
throw new InvalidOperationException("The parent is missing.");
185
int index = _parent.IndexOfItem(this);
186
_parent.AddInternal(index, content, false);
190
/// Returns a collection of the ancestor tokens of this token.
192
/// <returns>A collection of the ancestor tokens of this token.</returns>
193
public IEnumerable<JToken> Ancestors()
195
for (JToken parent = Parent; parent != null; parent = parent.Parent)
202
/// Returns a collection of the sibling tokens after this token, in document order.
204
/// <returns>A collection of the sibling tokens after this tokens, in document order.</returns>
205
public IEnumerable<JToken> AfterSelf()
210
for (JToken o = Next; o != null; o = o.Next)
217
/// Returns a collection of the sibling tokens before this token, in document order.
219
/// <returns>A collection of the sibling tokens before this token, in document order.</returns>
220
public IEnumerable<JToken> BeforeSelf()
222
for (JToken o = Parent.First; o != this; o = o.Next)
229
/// Gets the <see cref="JToken"/> with the specified key.
231
/// <value>The <see cref="JToken"/> with the specified key.</value>
232
public virtual JToken this[object key]
234
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); }
235
set { throw new InvalidOperationException("Cannot set child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); }
239
/// Gets the <see cref="JToken"/> with the specified key converted to the specified type.
241
/// <typeparam name="T">The type to convert the token to.</typeparam>
242
/// <param name="key">The token key.</param>
243
/// <returns>The converted token value.</returns>
244
public virtual T Value<T>(object key)
246
JToken token = this[key];
248
return Extensions.Convert<JToken, T>(token);
252
/// Get the first child token of this token.
254
/// <value>A <see cref="JToken"/> containing the first child token of the <see cref="JToken"/>.</value>
255
public virtual JToken First
257
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); }
261
/// Get the last child token of this token.
263
/// <value>A <see cref="JToken"/> containing the last child token of the <see cref="JToken"/>.</value>
264
public virtual JToken Last
266
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); }
270
/// Returns a collection of the child tokens of this token, in document order.
272
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> containing the child tokens of this <see cref="JToken"/>, in document order.</returns>
273
public virtual JEnumerable<JToken> Children()
275
return JEnumerable<JToken>.Empty;
279
/// Returns a collection of the child tokens of this token, in document order, filtered by the specified type.
281
/// <typeparam name="T">The type to filter the child tokens on.</typeparam>
282
/// <returns>A <see cref="JEnumerable{T}"/> containing the child tokens of this <see cref="JToken"/>, in document order.</returns>
283
public JEnumerable<T> Children<T>() where T : JToken
285
return new JEnumerable<T>(Children().OfType<T>());
289
/// Returns a collection of the child values of this token, in document order.
291
/// <typeparam name="T">The type to convert the values to.</typeparam>
292
/// <returns>A <see cref="IEnumerable{T}"/> containing the child values of this <see cref="JToken"/>, in document order.</returns>
293
public virtual IEnumerable<T> Values<T>()
295
throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
299
/// Removes this token from its parent.
304
throw new InvalidOperationException("The parent is missing.");
306
_parent.RemoveItem(this);
310
/// Replaces this token with the specified token.
312
/// <param name="value">The value.</param>
313
public void Replace(JToken value)
316
throw new InvalidOperationException("The parent is missing.");
318
_parent.ReplaceItem(this, value);
322
/// Writes this token to a <see cref="JsonWriter"/>.
324
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
325
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
326
public abstract void WriteTo(JsonWriter writer, params JsonConverter[] converters);
329
/// Returns the indented JSON for this token.
332
/// The indented JSON for this token.
334
public override string ToString()
336
return ToString(Formatting.Indented);
340
/// Returns the JSON for this token using the given formatting and converters.
342
/// <param name="formatting">Indicates how the output is formatted.</param>
343
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
344
/// <returns>The JSON for this token using the given formatting and converters.</returns>
345
public string ToString(Formatting formatting, params JsonConverter[] converters)
347
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
349
JsonTextWriter jw = new JsonTextWriter(sw);
350
jw.Formatting = formatting;
352
WriteTo(jw, converters);
354
return sw.ToString();
358
private static JValue EnsureValue(JToken value)
361
throw new ArgumentNullException("value");
363
if (value is JProperty)
364
value = ((JProperty)value).Value;
366
JValue v = value as JValue;
371
private static string GetType(JToken token)
373
ValidationUtils.ArgumentNotNull(token, "token");
375
if (token is JProperty)
376
token = ((JProperty)token).Value;
378
return token.Type.ToString();
381
private static bool IsNullable(JToken o)
383
return (o.Type == JTokenType.Undefined || o.Type == JTokenType.Null);
386
private static bool ValidateFloat(JToken o, bool nullable)
388
return (o.Type == JTokenType.Float || o.Type == JTokenType.Integer || (nullable && IsNullable(o)));
391
private static bool ValidateInteger(JToken o, bool nullable)
393
return (o.Type == JTokenType.Integer || (nullable && IsNullable(o)));
396
private static bool ValidateDate(JToken o, bool nullable)
398
return (o.Type == JTokenType.Date || (nullable && IsNullable(o)));
401
private static bool ValidateBoolean(JToken o, bool nullable)
403
return (o.Type == JTokenType.Boolean || (nullable && IsNullable(o)));
406
private static bool ValidateString(JToken o)
408
return (o.Type == JTokenType.String || o.Type == JTokenType.Comment || o.Type == JTokenType.Raw || IsNullable(o));
411
private static bool ValidateBytes(JToken o)
413
return (o.Type == JTokenType.Bytes || IsNullable(o));
416
#region Cast from operators
418
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Boolean"/>.
420
/// <param name="value">The value.</param>
421
/// <returns>The result of the conversion.</returns>
422
public static explicit operator bool(JToken value)
424
JValue v = EnsureValue(value);
425
if (v == null || !ValidateBoolean(v, false))
426
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
428
return Convert.ToBoolean(v.Value, CultureInfo.InvariantCulture);
431
#if !PocketPC && !NET20
433
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.DateTimeOffset"/>.
435
/// <param name="value">The value.</param>
436
/// <returns>The result of the conversion.</returns>
437
public static explicit operator DateTimeOffset(JToken value)
439
JValue v = EnsureValue(value);
440
if (v == null || !ValidateDate(v, false))
441
throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
443
return (DateTimeOffset)v.Value;
448
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Boolean}"/>.
450
/// <param name="value">The value.</param>
451
/// <returns>The result of the conversion.</returns>
452
public static explicit operator bool?(JToken value)
457
JValue v = EnsureValue(value);
458
if (v == null || !ValidateBoolean(v, true))
459
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
461
return (v.Value != null) ? (bool?)Convert.ToBoolean(v.Value, CultureInfo.InvariantCulture) : null;
465
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Int64"/>.
467
/// <param name="value">The value.</param>
468
/// <returns>The result of the conversion.</returns>
469
public static explicit operator long(JToken value)
471
JValue v = EnsureValue(value);
472
if (v == null || !ValidateInteger(v, false))
473
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
475
return Convert.ToInt64(v.Value, CultureInfo.InvariantCulture);
479
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{DateTime}"/>.
481
/// <param name="value">The value.</param>
482
/// <returns>The result of the conversion.</returns>
483
public static explicit operator DateTime?(JToken value)
488
JValue v = EnsureValue(value);
489
if (v == null || !ValidateDate(v, true))
490
throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
492
return (v.Value != null) ? (DateTime?)Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture) : null;
495
#if !PocketPC && !NET20
497
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{DateTimeOffset}"/>.
499
/// <param name="value">The value.</param>
500
/// <returns>The result of the conversion.</returns>
501
public static explicit operator DateTimeOffset?(JToken value)
506
JValue v = EnsureValue(value);
507
if (v == null || !ValidateDate(v, true))
508
throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
510
return (DateTimeOffset?)v.Value;
515
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Decimal}"/>.
517
/// <param name="value">The value.</param>
518
/// <returns>The result of the conversion.</returns>
519
public static explicit operator decimal?(JToken value)
524
JValue v = EnsureValue(value);
525
if (v == null || !ValidateFloat(v, true))
526
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
528
return (v.Value != null) ? (decimal?)Convert.ToDecimal(v.Value, CultureInfo.InvariantCulture) : null;
532
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Double}"/>.
534
/// <param name="value">The value.</param>
535
/// <returns>The result of the conversion.</returns>
536
public static explicit operator double?(JToken value)
541
JValue v = EnsureValue(value);
542
if (v == null || !ValidateFloat(v, true))
543
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
545
return (double?)v.Value;
549
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Int32"/>.
551
/// <param name="value">The value.</param>
552
/// <returns>The result of the conversion.</returns>
553
public static explicit operator int(JToken value)
555
JValue v = EnsureValue(value);
556
if (v == null || !ValidateInteger(v, false))
557
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
559
return Convert.ToInt32(v.Value, CultureInfo.InvariantCulture);
563
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Int16"/>.
565
/// <param name="value">The value.</param>
566
/// <returns>The result of the conversion.</returns>
567
public static explicit operator short(JToken value)
569
JValue v = EnsureValue(value);
570
if (v == null || !ValidateInteger(v, false))
571
throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
573
return Convert.ToInt16(v.Value, CultureInfo.InvariantCulture);
577
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.UInt16"/>.
579
/// <param name="value">The value.</param>
580
/// <returns>The result of the conversion.</returns>
581
[CLSCompliant(false)]
582
public static explicit operator ushort(JToken value)
584
JValue v = EnsureValue(value);
585
if (v == null || !ValidateInteger(v, false))
586
throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
588
return Convert.ToUInt16(v.Value, CultureInfo.InvariantCulture);
592
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Int32}"/>.
594
/// <param name="value">The value.</param>
595
/// <returns>The result of the conversion.</returns>
596
public static explicit operator int?(JToken value)
601
JValue v = EnsureValue(value);
602
if (v == null || !ValidateInteger(v, true))
603
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
605
return (v.Value != null) ? (int?)Convert.ToInt32(v.Value, CultureInfo.InvariantCulture) : null;
609
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Int16}"/>.
611
/// <param name="value">The value.</param>
612
/// <returns>The result of the conversion.</returns>
613
public static explicit operator short?(JToken value)
618
JValue v = EnsureValue(value);
619
if (v == null || !ValidateInteger(v, true))
620
throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
622
return (v.Value != null) ? (short?)Convert.ToInt16(v.Value, CultureInfo.InvariantCulture) : null;
626
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{UInt16}"/>.
628
/// <param name="value">The value.</param>
629
/// <returns>The result of the conversion.</returns>
630
[CLSCompliant(false)]
631
public static explicit operator ushort?(JToken value)
636
JValue v = EnsureValue(value);
637
if (v == null || !ValidateInteger(v, true))
638
throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
640
return (v.Value != null) ? (ushort?)Convert.ToInt16(v.Value, CultureInfo.InvariantCulture) : null;
644
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.DateTime"/>.
646
/// <param name="value">The value.</param>
647
/// <returns>The result of the conversion.</returns>
648
public static explicit operator DateTime(JToken value)
650
JValue v = EnsureValue(value);
651
if (v == null || !ValidateDate(v, false))
652
throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
654
return Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture);
658
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Int64}"/>.
660
/// <param name="value">The value.</param>
661
/// <returns>The result of the conversion.</returns>
662
public static explicit operator long?(JToken value)
667
JValue v = EnsureValue(value);
668
if (v == null || !ValidateInteger(v, true))
669
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
671
return (v.Value != null) ? (long?)Convert.ToInt64(v.Value, CultureInfo.InvariantCulture) : null;
675
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{Single}"/>.
677
/// <param name="value">The value.</param>
678
/// <returns>The result of the conversion.</returns>
679
public static explicit operator float?(JToken value)
684
JValue v = EnsureValue(value);
685
if (v == null || !ValidateFloat(v, true))
686
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
688
return (v.Value != null) ? (float?)Convert.ToSingle(v.Value, CultureInfo.InvariantCulture) : null;
692
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Decimal"/>.
694
/// <param name="value">The value.</param>
695
/// <returns>The result of the conversion.</returns>
696
public static explicit operator decimal(JToken value)
698
JValue v = EnsureValue(value);
699
if (v == null || !ValidateFloat(v, false))
700
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
702
return Convert.ToDecimal(v.Value, CultureInfo.InvariantCulture);
706
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{UInt32}"/>.
708
/// <param name="value">The value.</param>
709
/// <returns>The result of the conversion.</returns>
710
[CLSCompliant(false)]
711
public static explicit operator uint?(JToken value)
716
JValue v = EnsureValue(value);
717
if (v == null || !ValidateInteger(v, true))
718
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
720
return (v.Value != null) ? (uint?)Convert.ToUInt32(v.Value, CultureInfo.InvariantCulture) : null;
724
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{UInt64}"/>.
726
/// <param name="value">The value.</param>
727
/// <returns>The result of the conversion.</returns>
728
[CLSCompliant(false)]
729
public static explicit operator ulong?(JToken value)
734
JValue v = EnsureValue(value);
735
if (v == null || !ValidateInteger(v, true))
736
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
738
return (v.Value != null) ? (ulong?)Convert.ToUInt64(v.Value, CultureInfo.InvariantCulture) : null;
742
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Double"/>.
744
/// <param name="value">The value.</param>
745
/// <returns>The result of the conversion.</returns>
746
public static explicit operator double(JToken value)
748
JValue v = EnsureValue(value);
749
if (v == null || !ValidateFloat(v, false))
750
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
752
return Convert.ToDouble(v.Value, CultureInfo.InvariantCulture);
756
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.Single"/>.
758
/// <param name="value">The value.</param>
759
/// <returns>The result of the conversion.</returns>
760
public static explicit operator float(JToken value)
762
JValue v = EnsureValue(value);
763
if (v == null || !ValidateFloat(v, false))
764
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
766
return Convert.ToSingle(v.Value, CultureInfo.InvariantCulture);
770
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.String"/>.
772
/// <param name="value">The value.</param>
773
/// <returns>The result of the conversion.</returns>
774
public static explicit operator string(JToken value)
779
JValue v = EnsureValue(value);
780
if (v == null || !ValidateString(v))
781
throw new ArgumentException("Can not convert {0} to String.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
783
return (v.Value != null) ? Convert.ToString(v.Value, CultureInfo.InvariantCulture) : null;
787
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.UInt32"/>.
789
/// <param name="value">The value.</param>
790
/// <returns>The result of the conversion.</returns>
791
[CLSCompliant(false)]
792
public static explicit operator uint(JToken value)
794
JValue v = EnsureValue(value);
795
if (v == null || !ValidateInteger(v, false))
796
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
798
return Convert.ToUInt32(v.Value, CultureInfo.InvariantCulture);
802
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="System.UInt64"/>.
804
/// <param name="value">The value.</param>
805
/// <returns>The result of the conversion.</returns>
806
[CLSCompliant(false)]
807
public static explicit operator ulong(JToken value)
809
JValue v = EnsureValue(value);
810
if (v == null || !ValidateInteger(v, false))
811
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
813
return Convert.ToUInt64(v.Value, CultureInfo.InvariantCulture);
817
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="T:System.Byte[]"/>.
819
/// <param name="value">The value.</param>
820
/// <returns>The result of the conversion.</returns>
821
public static explicit operator byte[](JToken value)
823
JValue v = EnsureValue(value);
824
if (v == null || !ValidateBytes(v))
825
throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
827
return (byte[])v.Value;
831
#region Cast to operators
833
/// Performs an implicit conversion from <see cref="Boolean"/> to <see cref="JToken"/>.
835
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
836
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
837
public static implicit operator JToken(bool value)
839
return new JValue(value);
842
#if !PocketPC && !NET20
844
/// Performs an implicit conversion from <see cref="DateTimeOffset"/> to <see cref="JToken"/>.
846
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
847
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
848
public static implicit operator JToken(DateTimeOffset value)
850
return new JValue(value);
855
/// Performs an implicit conversion from <see cref="Nullable{Boolean}"/> to <see cref="JToken"/>.
857
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
858
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
859
public static implicit operator JToken(bool? value)
861
return new JValue(value);
865
/// Performs an implicit conversion from <see cref="Nullable{Int64}"/> to <see cref="JToken"/>.
867
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
868
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
869
public static implicit operator JToken(long value)
871
return new JValue(value);
875
/// Performs an implicit conversion from <see cref="Nullable{DateTime}"/> to <see cref="JToken"/>.
877
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
878
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
879
public static implicit operator JToken(DateTime? value)
881
return new JValue(value);
884
#if !PocketPC && !NET20
886
/// Performs an implicit conversion from <see cref="Nullable{DateTimeOffset}"/> to <see cref="JToken"/>.
888
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
889
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
890
public static implicit operator JToken(DateTimeOffset? value)
892
return new JValue(value);
897
/// Performs an implicit conversion from <see cref="Nullable{Decimal}"/> to <see cref="JToken"/>.
899
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
900
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
901
public static implicit operator JToken(decimal? value)
903
return new JValue(value);
907
/// Performs an implicit conversion from <see cref="Nullable{Double}"/> to <see cref="JToken"/>.
909
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
910
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
911
public static implicit operator JToken(double? value)
913
return new JValue(value);
917
/// Performs an implicit conversion from <see cref="Int16"/> to <see cref="JToken"/>.
919
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
920
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
921
[CLSCompliant(false)]
922
public static implicit operator JToken(short value)
924
return new JValue(value);
928
/// Performs an implicit conversion from <see cref="UInt16"/> to <see cref="JToken"/>.
930
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
931
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
932
[CLSCompliant(false)]
933
public static implicit operator JToken(ushort value)
935
return new JValue(value);
939
/// Performs an implicit conversion from <see cref="Int32"/> to <see cref="JToken"/>.
941
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
942
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
943
public static implicit operator JToken(int value)
945
return new JValue(value);
949
/// Performs an implicit conversion from <see cref="Nullable{Int32}"/> to <see cref="JToken"/>.
951
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
952
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
953
public static implicit operator JToken(int? value)
955
return new JValue(value);
959
/// Performs an implicit conversion from <see cref="DateTime"/> to <see cref="JToken"/>.
961
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
962
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
963
public static implicit operator JToken(DateTime value)
965
return new JValue(value);
969
/// Performs an implicit conversion from <see cref="Nullable{Int64}"/> to <see cref="JToken"/>.
971
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
972
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
973
public static implicit operator JToken(long? value)
975
return new JValue(value);
979
/// Performs an implicit conversion from <see cref="Nullable{Single}"/> to <see cref="JToken"/>.
981
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
982
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
983
public static implicit operator JToken(float? value)
985
return new JValue(value);
989
/// Performs an implicit conversion from <see cref="Decimal"/> to <see cref="JToken"/>.
991
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
992
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
993
public static implicit operator JToken(decimal value)
995
return new JValue(value);
999
/// Performs an implicit conversion from <see cref="Nullable{Int16}"/> to <see cref="JToken"/>.
1001
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1002
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1003
[CLSCompliant(false)]
1004
public static implicit operator JToken(short? value)
1006
return new JValue(value);
1010
/// Performs an implicit conversion from <see cref="Nullable{UInt16}"/> to <see cref="JToken"/>.
1012
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1013
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1014
[CLSCompliant(false)]
1015
public static implicit operator JToken(ushort? value)
1017
return new JValue(value);
1021
/// Performs an implicit conversion from <see cref="Nullable{UInt32}"/> to <see cref="JToken"/>.
1023
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1024
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1025
[CLSCompliant(false)]
1026
public static implicit operator JToken(uint? value)
1028
return new JValue(value);
1032
/// Performs an implicit conversion from <see cref="Nullable{UInt64}"/> to <see cref="JToken"/>.
1034
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1035
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1036
[CLSCompliant(false)]
1037
public static implicit operator JToken(ulong? value)
1039
return new JValue(value);
1043
/// Performs an implicit conversion from <see cref="Double"/> to <see cref="JToken"/>.
1045
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1046
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1047
public static implicit operator JToken(double value)
1049
return new JValue(value);
1053
/// Performs an implicit conversion from <see cref="Single"/> to <see cref="JToken"/>.
1055
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1056
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1057
public static implicit operator JToken(float value)
1059
return new JValue(value);
1063
/// Performs an implicit conversion from <see cref="String"/> to <see cref="JToken"/>.
1065
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1066
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1067
public static implicit operator JToken(string value)
1069
return new JValue(value);
1073
/// Performs an implicit conversion from <see cref="UInt32"/> to <see cref="JToken"/>.
1075
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1076
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1077
[CLSCompliant(false)]
1078
public static implicit operator JToken(uint value)
1080
return new JValue(value);
1084
/// Performs an implicit conversion from <see cref="UInt64"/> to <see cref="JToken"/>.
1086
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1087
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1088
[CLSCompliant(false)]
1089
public static implicit operator JToken(ulong value)
1091
return new JValue(value);
1095
/// Performs an implicit conversion from <see cref="T:System.Byte[]"/> to <see cref="Newtonsoft.Json.Linq.JToken"/>.
1097
/// <param name="value">The value to create a <see cref="JValue"/> from.</param>
1098
/// <returns>The <see cref="JValue"/> initialized with the specified value.</returns>
1099
public static implicit operator JToken(byte[] value)
1101
return new JValue(value);
1105
IEnumerator IEnumerable.GetEnumerator()
1107
return ((IEnumerable<JToken>)this).GetEnumerator();
1110
IEnumerator<JToken> IEnumerable<JToken>.GetEnumerator()
1112
return Children().GetEnumerator();
1115
internal abstract int GetDeepHashCode();
1117
IJEnumerable<JToken> IJEnumerable<JToken>.this[object key]
1119
get { return this[key]; }
1123
/// Creates an <see cref="JsonReader"/> for this token.
1125
/// <returns>An <see cref="JsonReader"/> that can be used to read this token and its descendants.</returns>
1126
public JsonReader CreateReader()
1128
return new JTokenReader(this);
1131
internal static JToken FromObjectInternal(object o, JsonSerializer jsonSerializer)
1133
ValidationUtils.ArgumentNotNull(o, "o");
1134
ValidationUtils.ArgumentNotNull(jsonSerializer, "jsonSerializer");
1137
using (JTokenWriter jsonWriter = new JTokenWriter())
1139
jsonSerializer.Serialize(jsonWriter, o);
1140
token = jsonWriter.Token;
1147
/// Creates a <see cref="JToken"/> from an object.
1149
/// <param name="o">The object that will be used to create <see cref="JToken"/>.</param>
1150
/// <returns>A <see cref="JToken"/> with the value of the specified object</returns>
1151
public static JToken FromObject(object o)
1153
return FromObjectInternal(o, new JsonSerializer());
1157
/// Creates a <see cref="JToken"/> from an object using the specified <see cref="JsonSerializer"/>.
1159
/// <param name="o">The object that will be used to create <see cref="JToken"/>.</param>
1160
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when reading the object.</param>
1161
/// <returns>A <see cref="JToken"/> with the value of the specified object</returns>
1162
public static JToken FromObject(object o, JsonSerializer jsonSerializer)
1164
return FromObjectInternal(o, jsonSerializer);
1168
/// Creates the specified .NET type from the <see cref="JToken"/>.
1170
/// <typeparam name="T">The object type that the token will be deserialized to.</typeparam>
1171
/// <returns>The new object created from the JSON value.</returns>
1172
public T ToObject<T>()
1174
return ToObject<T>(new JsonSerializer());
1178
/// Creates the specified .NET type from the <see cref="JToken"/> using the specified <see cref="JsonSerializer"/>.
1180
/// <typeparam name="T">The object type that the token will be deserialized to.</typeparam>
1181
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when creating the object.</param>
1182
/// <returns>The new object created from the JSON value.</returns>
1183
public T ToObject<T>(JsonSerializer jsonSerializer)
1185
ValidationUtils.ArgumentNotNull(jsonSerializer, "jsonSerializer");
1187
using (JTokenReader jsonReader = new JTokenReader(this))
1189
return jsonSerializer.Deserialize<T>(jsonReader);
1194
/// Creates a <see cref="JToken"/> from a <see cref="JsonReader"/>.
1196
/// <param name="reader">An <see cref="JsonReader"/> positioned at the token to read into this <see cref="JToken"/>.</param>
1198
/// An <see cref="JToken"/> that contains the token and its descendant tokens
1199
/// that were read from the reader. The runtime type of the token is determined
1200
/// by the token type of the first token encountered in the reader.
1202
public static JToken ReadFrom(JsonReader reader)
1204
ValidationUtils.ArgumentNotNull(reader, "reader");
1206
if (reader.TokenType == JsonToken.None)
1209
throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader.");
1212
if (reader.TokenType == JsonToken.StartObject)
1213
return JObject.Load(reader);
1215
if (reader.TokenType == JsonToken.StartArray)
1216
return JArray.Load(reader);
1218
if (reader.TokenType == JsonToken.PropertyName)
1219
return JProperty.Load(reader);
1221
if (reader.TokenType == JsonToken.StartConstructor)
1222
return JConstructor.Load(reader);
1224
if (!JsonReader.IsStartToken(reader.TokenType))
1225
return new JValue(reader.Value);
1227
throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
1231
/// Load a <see cref="JToken"/> from a string that contains JSON.
1233
/// <param name="json">A <see cref="String"/> that contains JSON.</param>
1234
/// <returns>A <see cref="JToken"/> populated from the string that contains JSON.</returns>
1235
public static JToken Parse(string json)
1237
JsonReader reader = new JsonTextReader(new StringReader(json));
1239
JToken t = Load(reader);
1241
if (reader.Read() && reader.TokenType != JsonToken.Comment)
1242
throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
1248
/// Creates a <see cref="JToken"/> from a <see cref="JsonReader"/>.
1250
/// <param name="reader">An <see cref="JsonReader"/> positioned at the token to read into this <see cref="JToken"/>.</param>
1252
/// An <see cref="JToken"/> that contains the token and its descendant tokens
1253
/// that were read from the reader. The runtime type of the token is determined
1254
/// by the token type of the first token encountered in the reader.
1256
public static JToken Load(JsonReader reader)
1258
return ReadFrom(reader);
1261
internal void SetLineInfo(IJsonLineInfo lineInfo)
1263
if (lineInfo == null || !lineInfo.HasLineInfo())
1266
SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition);
1269
internal void SetLineInfo(int lineNumber, int linePosition)
1271
_lineNumber = lineNumber;
1272
_linePosition = linePosition;
1275
bool IJsonLineInfo.HasLineInfo()
1277
return (_lineNumber != null && _linePosition != null);
1280
int IJsonLineInfo.LineNumber
1282
get { return _lineNumber ?? 0; }
1285
int IJsonLineInfo.LinePosition
1287
get { return _linePosition ?? 0; }
1291
/// Selects the token that matches the object path.
1293
/// <param name="path">
1294
/// The object path from the current <see cref="JToken"/> to the <see cref="JToken"/>
1295
/// to be returned. This must be a string of property names or array indexes separated
1296
/// by periods, such as <code>Tables[0].DefaultView[0].Price</code> in C# or
1297
/// <code>Tables(0).DefaultView(0).Price</code> in Visual Basic.
1299
/// <returns>The <see cref="JToken"/> that matches the object path or a null reference if no matching token is found.</returns>
1300
public JToken SelectToken(string path)
1302
return SelectToken(path, false);
1306
/// Selects the token that matches the object path.
1308
/// <param name="path">
1309
/// The object path from the current <see cref="JToken"/> to the <see cref="JToken"/>
1310
/// to be returned. This must be a string of property names or array indexes separated
1311
/// by periods, such as <code>Tables[0].DefaultView[0].Price</code> in C# or
1312
/// <code>Tables(0).DefaultView(0).Price</code> in Visual Basic.
1314
/// <param name="errorWhenNoMatch">A flag to indicate whether an error should be thrown if no token is found.</param>
1315
/// <returns>The <see cref="JToken"/> that matches the object path.</returns>
1316
public JToken SelectToken(string path, bool errorWhenNoMatch)
1318
JPath p = new JPath(path);
1319
return p.Evaluate(this, errorWhenNoMatch);
1322
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
1324
/// Returns the <see cref="T:System.Dynamic.DynamicMetaObject"/> responsible for binding operations performed on this object.
1326
/// <param name="parameter">The expression tree representation of the runtime value.</param>
1328
/// The <see cref="T:System.Dynamic.DynamicMetaObject"/> to bind this object.
1330
protected virtual DynamicMetaObject GetMetaObject(Expression parameter)
1332
return new DynamicProxyMetaObject<JToken>(parameter, this, new DynamicProxy<JToken>(), true);
1336
/// Returns the <see cref="T:System.Dynamic.DynamicMetaObject"/> responsible for binding operations performed on this object.
1338
/// <param name="parameter">The expression tree representation of the runtime value.</param>
1340
/// The <see cref="T:System.Dynamic.DynamicMetaObject"/> to bind this object.
1342
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter)
1344
return GetMetaObject(parameter);
1348
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
1349
object ICloneable.Clone()
1356
/// Creates a new instance of the <see cref="JToken"/>. All child tokens are recursively cloned.
1358
/// <returns>A new instance of the <see cref="JToken"/>.</returns>
1359
public JToken DeepClone()
1361
return CloneToken();
b'\\ No newline at end of file'