2 using System.Collections.Generic;
3 using System.ComponentModel;
6 using Newtonsoft.Json.Tests.TestObjects;
8 using Newtonsoft.Json.Linq;
9 using Newtonsoft.Json.Converters;
11 using System.Collections;
12 using System.Collections.Specialized;
13 #if !PocketPC && !SILVERLIGHT
17 namespace Newtonsoft.Json.Tests.Linq
19 public class JObjectTests : TestFixtureBase
22 public void TryGetValue()
24 JObject o = new JObject();
25 o.Add("PropertyNameValue", new JValue(1));
26 Assert.AreEqual(1, o.Children().Count());
29 Assert.AreEqual(false, o.TryGetValue("sdf", out t));
30 Assert.AreEqual(null, t);
32 Assert.AreEqual(false, o.TryGetValue(null, out t));
33 Assert.AreEqual(null, t);
35 Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
36 Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
40 public void DictionaryItemShouldSet()
42 JObject o = new JObject();
43 o["PropertyNameValue"] = new JValue(1);
44 Assert.AreEqual(1, o.Children().Count());
47 Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
48 Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
50 o["PropertyNameValue"] = new JValue(2);
51 Assert.AreEqual(1, o.Children().Count());
53 Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
54 Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t));
56 o["PropertyNameValue"] = null;
57 Assert.AreEqual(1, o.Children().Count());
59 Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
60 Assert.AreEqual(true, JToken.DeepEquals(new JValue((object)null), t));
66 JObject o = new JObject();
67 o.Add("PropertyNameValue", new JValue(1));
68 Assert.AreEqual(1, o.Children().Count());
70 Assert.AreEqual(false, o.Remove("sdf"));
71 Assert.AreEqual(false, o.Remove(null));
72 Assert.AreEqual(true, o.Remove("PropertyNameValue"));
74 Assert.AreEqual(0, o.Children().Count());
78 public void GenericCollectionRemove()
80 JValue v = new JValue(1);
81 JObject o = new JObject();
82 o.Add("PropertyNameValue", v);
83 Assert.AreEqual(1, o.Children().Count());
85 Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))));
86 Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))));
87 Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))));
88 Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v)));
90 Assert.AreEqual(0, o.Children().Count());
94 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
95 public void DuplicatePropertyNameShouldThrow()
97 JObject o = new JObject();
98 o.Add("PropertyNameValue", null);
99 o.Add("PropertyNameValue", null);
103 public void GenericDictionaryAdd()
105 JObject o = new JObject();
107 o.Add("PropertyNameValue", new JValue(1));
108 Assert.AreEqual(1, (int)o["PropertyNameValue"]);
110 o.Add("PropertyNameValue1", null);
111 Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value);
113 Assert.AreEqual(2, o.Children().Count());
117 public void GenericCollectionAdd()
119 JObject o = new JObject();
120 ((ICollection<KeyValuePair<string,JToken>>)o).Add(new KeyValuePair<string,JToken>("PropertyNameValue", new JValue(1)));
122 Assert.AreEqual(1, (int)o["PropertyNameValue"]);
123 Assert.AreEqual(1, o.Children().Count());
127 public void GenericCollectionClear()
129 JObject o = new JObject();
130 o.Add("PropertyNameValue", new JValue(1));
131 Assert.AreEqual(1, o.Children().Count());
133 JProperty p = (JProperty)o.Children().ElementAt(0);
135 ((ICollection<KeyValuePair<string, JToken>>)o).Clear();
136 Assert.AreEqual(0, o.Children().Count());
138 Assert.AreEqual(null, p.Parent);
142 public void GenericCollectionContains()
144 JValue v = new JValue(1);
145 JObject o = new JObject();
146 o.Add("PropertyNameValue", v);
147 Assert.AreEqual(1, o.Children().Count());
149 bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
150 Assert.AreEqual(false, contains);
152 contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v));
153 Assert.AreEqual(true, contains);
155 contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)));
156 Assert.AreEqual(false, contains);
158 contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)));
159 Assert.AreEqual(false, contains);
161 contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>));
162 Assert.AreEqual(false, contains);
166 public void GenericDictionaryContains()
168 JObject o = new JObject();
169 o.Add("PropertyNameValue", new JValue(1));
170 Assert.AreEqual(1, o.Children().Count());
172 bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue");
173 Assert.AreEqual(true, contains);
177 public void GenericCollectionCopyTo()
179 JObject o = new JObject();
180 o.Add("PropertyNameValue", new JValue(1));
181 o.Add("PropertyNameValue2", new JValue(2));
182 o.Add("PropertyNameValue3", new JValue(3));
183 Assert.AreEqual(3, o.Children().Count());
185 KeyValuePair<string, JToken>[] a = new KeyValuePair<string,JToken>[5];
187 ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1);
189 Assert.AreEqual(default(KeyValuePair<string,JToken>), a[0]);
191 Assert.AreEqual("PropertyNameValue", a[1].Key);
192 Assert.AreEqual(1, (int)a[1].Value);
194 Assert.AreEqual("PropertyNameValue2", a[2].Key);
195 Assert.AreEqual(2, (int)a[2].Value);
197 Assert.AreEqual("PropertyNameValue3", a[3].Key);
198 Assert.AreEqual(3, (int)a[3].Value);
200 Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]);
204 [ExpectedException(typeof(ArgumentNullException), ExpectedMessage = @"Value cannot be null.
205 Parameter name: array")]
206 public void GenericCollectionCopyToNullArrayShouldThrow()
208 JObject o = new JObject();
209 ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
213 [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"arrayIndex is less than 0.
214 Parameter name: arrayIndex")]
215 public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
217 JObject o = new JObject();
218 ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
222 [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"arrayIndex is equal to or greater than the length of array.")]
223 public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
225 JObject o = new JObject();
226 ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
230 [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.")]
231 public void GenericCollectionCopyToInsufficientArrayCapacity()
233 JObject o = new JObject();
234 o.Add("PropertyNameValue", new JValue(1));
235 o.Add("PropertyNameValue2", new JValue(2));
236 o.Add("PropertyNameValue3", new JValue(3));
238 ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
242 public void FromObjectRaw()
244 PersonRaw raw = new PersonRaw
246 FirstName = "FirstNameValue",
247 RawContent = new JRaw("[1,2,3,4,5]"),
248 LastName = "LastNameValue"
251 JObject o = JObject.FromObject(raw);
253 Assert.AreEqual("FirstNameValue", (string)o["first_name"]);
254 Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type);
255 Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]);
256 Assert.AreEqual("LastNameValue", (string)o["last_name"]);
260 public void JTokenReader()
262 PersonRaw raw = new PersonRaw
264 FirstName = "FirstNameValue",
265 RawContent = new JRaw("[1,2,3,4,5]"),
266 LastName = "LastNameValue"
269 JObject o = JObject.FromObject(raw);
271 JsonReader reader = new JTokenReader(o);
273 Assert.IsTrue(reader.Read());
274 Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
276 Assert.IsTrue(reader.Read());
277 Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
279 Assert.IsTrue(reader.Read());
280 Assert.AreEqual(JsonToken.String, reader.TokenType);
282 Assert.IsTrue(reader.Read());
283 Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
285 Assert.IsTrue(reader.Read());
286 Assert.AreEqual(JsonToken.Raw, reader.TokenType);
288 Assert.IsTrue(reader.Read());
289 Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
291 Assert.IsTrue(reader.Read());
292 Assert.AreEqual(JsonToken.String, reader.TokenType);
294 Assert.IsTrue(reader.Read());
295 Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
297 Assert.IsFalse(reader.Read());
301 public void DeserializeFromRaw()
303 PersonRaw raw = new PersonRaw
305 FirstName = "FirstNameValue",
306 RawContent = new JRaw("[1,2,3,4,5]"),
307 LastName = "LastNameValue"
310 JObject o = JObject.FromObject(raw);
312 JsonReader reader = new JTokenReader(o);
313 JsonSerializer serializer = new JsonSerializer();
314 raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw));
316 Assert.AreEqual("FirstNameValue", raw.FirstName);
317 Assert.AreEqual("LastNameValue", raw.LastName);
318 Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value);
322 [ExpectedException(typeof(Exception), ExpectedMessage = "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray")]
323 public void Parse_ShouldThrowOnUnexpectedToken()
325 string json = @"[""prop""]";
330 public void ParseJavaScriptDate()
332 string json = @"[new Date(1207285200000)]";
334 JArray a = (JArray)JsonConvert.DeserializeObject(json);
335 JValue v = (JValue)a[0];
337 Assert.AreEqual(JsonConvert.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v);
341 public void GenericValueCast()
343 string json = @"{""foo"":true}";
344 JObject o = (JObject)JsonConvert.DeserializeObject(json);
345 bool? value = o.Value<bool?>("foo");
346 Assert.AreEqual(true, value);
348 json = @"{""foo"":null}";
349 o = (JObject)JsonConvert.DeserializeObject(json);
350 value = o.Value<bool?>("foo");
351 Assert.AreEqual(null, value);
355 [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Invalid property identifier character: ]. Line 3, position 9.")]
358 JObject person = JObject.Parse(@"{
360 ]!#$THIS IS: BAD JSON![{}}}}]
363 // Invalid property identifier character: ]. Line 3, position 9.
367 public void RawChildValues()
369 JObject o = new JObject();
370 o["val1"] = new JRaw("1");
371 o["val2"] = new JRaw("1");
373 string json = o.ToString();
382 public void Iterate()
384 JObject o = new JObject();
385 o.Add("PropertyNameValue1", new JValue(1));
386 o.Add("PropertyNameValue2", new JValue(2));
391 foreach (JProperty property in t)
393 Assert.AreEqual("PropertyNameValue" + i, property.Name);
394 Assert.AreEqual(i, (int)property.Value);
401 public void KeyValuePairIterate()
403 JObject o = new JObject();
404 o.Add("PropertyNameValue1", new JValue(1));
405 o.Add("PropertyNameValue2", new JValue(2));
408 foreach (KeyValuePair<string, JToken> pair in o)
410 Assert.AreEqual("PropertyNameValue" + i, pair.Key);
411 Assert.AreEqual(i, (int)pair.Value);
418 public void WriteObjectNullStringValue()
421 JValue v = new JValue(s);
422 Assert.AreEqual(null, v.Value);
423 Assert.AreEqual(JTokenType.String, v.Type);
425 JObject o = new JObject();
428 string output = o.ToString();
436 public void Example()
440 ""Expiry"": new Date(1230422400000),
449 JObject o = JObject.Parse(json);
451 string name = (string)o["Name"];
454 JArray sizes = (JArray)o["Sizes"];
456 string smallest = (string)sizes[0];
459 Console.WriteLine(name);
460 Console.WriteLine(smallest);
464 public void DeserializeClassManually()
466 string jsonText = @"{
469 ""original"":""http://www.foo.com/"",
470 ""short"":""krehqk"",
474 ""msg"":""No action taken""
479 JObject json = JObject.Parse(jsonText);
481 Shortie shortie = new Shortie
483 Original = (string)json["short"]["original"],
484 Short = (string)json["short"]["short"],
485 Error = new ShortieException
487 Code = (int)json["short"]["error"]["code"],
488 ErrorMessage = (string)json["short"]["error"]["msg"]
492 Console.WriteLine(shortie.Original);
493 // http://www.foo.com/
495 Console.WriteLine(shortie.Error.ErrorMessage);
498 Assert.AreEqual("http://www.foo.com/", shortie.Original);
499 Assert.AreEqual("krehqk", shortie.Short);
500 Assert.AreEqual(null, shortie.Shortened);
501 Assert.AreEqual(0, shortie.Error.Code);
502 Assert.AreEqual("No action taken", shortie.Error.ErrorMessage);
506 public void JObjectContainingHtml()
508 JObject o = new JObject();
509 o["rc"] = new JValue(200);
510 o["m"] = new JValue("");
511 o["o"] = new JValue(@"<div class='s1'>
513 <a href='asdf'>asdf</a><br />
528 ""o"": ""<div class='s1'>\r\n <div class='avatar'> \r\n <a href='asdf'>asdf</a><br />\r\n <strong>0</strong>\r\n </div>\r\n <div class='sl'>\r\n <p>\r\n 444444444\r\n </p>\r\n </div>\r\n <div class='clear'>\r\n </div> \r\n</div>""
533 public void ImplicitValueConversions()
535 JObject moss = new JObject();
536 moss["FirstName"] = new JValue("Maurice");
537 moss["LastName"] = new JValue("Moss");
538 moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30));
539 moss["Department"] = new JValue("IT");
540 moss["JobTitle"] = new JValue("Support");
542 Console.WriteLine(moss.ToString());
544 // "FirstName": "Maurice",
545 // "LastName": "Moss",
546 // "BirthDate": "\/Date(252241200000+1300)\/",
547 // "Department": "IT",
548 // "JobTitle": "Support"
552 JObject jen = new JObject();
553 jen["FirstName"] = "Jen";
554 jen["LastName"] = "Barber";
555 jen["BirthDate"] = new DateTime(1978, 3, 15);
556 jen["Department"] = "IT";
557 jen["JobTitle"] = "Manager";
559 Console.WriteLine(jen.ToString());
561 // "FirstName": "Jen",
562 // "LastName": "Barber",
563 // "BirthDate": "\/Date(258721200000+1300)\/",
564 // "Department": "IT",
565 // "JobTitle": "Manager"
570 public void ReplaceJPropertyWithJPropertyWithSameName()
572 JProperty p1 = new JProperty("Test1", 1);
573 JProperty p2 = new JProperty("Test2", "Two");
575 JObject o = new JObject(p1, p2);
577 Assert.AreEqual(p1, l[0]);
578 Assert.AreEqual(p2, l[1]);
580 JProperty p3 = new JProperty("Test1", "III");
583 Assert.AreEqual(null, p1.Parent);
584 Assert.AreEqual(l, p3.Parent);
586 Assert.AreEqual(p3, l[0]);
587 Assert.AreEqual(p2, l[1]);
589 Assert.AreEqual(2, l.Count);
590 Assert.AreEqual(2, o.Properties().Count());
592 JProperty p4 = new JProperty("Test4", "IV");
595 Assert.AreEqual(null, p2.Parent);
596 Assert.AreEqual(l, p4.Parent);
598 Assert.AreEqual(p3, l[0]);
599 Assert.AreEqual(p4, l[1]);
602 #if !PocketPC && !SILVERLIGHT && !NET20
604 public void PropertyChanging()
606 object changing = null;
607 object changed = null;
608 int changingCount = 0;
609 int changedCount = 0;
611 JObject o = new JObject();
612 o.PropertyChanging += (sender, args) =>
614 JObject s = (JObject) sender;
615 changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
618 o.PropertyChanged += (sender, args) =>
620 JObject s = (JObject)sender;
621 changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
625 o["StringValue"] = "value1";
626 Assert.AreEqual(null, changing);
627 Assert.AreEqual("value1", changed);
628 Assert.AreEqual("value1", (string)o["StringValue"]);
629 Assert.AreEqual(1, changingCount);
630 Assert.AreEqual(1, changedCount);
632 o["StringValue"] = "value1";
633 Assert.AreEqual(1, changingCount);
634 Assert.AreEqual(1, changedCount);
636 o["StringValue"] = "value2";
637 Assert.AreEqual("value1", changing);
638 Assert.AreEqual("value2", changed);
639 Assert.AreEqual("value2", (string)o["StringValue"]);
640 Assert.AreEqual(2, changingCount);
641 Assert.AreEqual(2, changedCount);
643 o["StringValue"] = null;
644 Assert.AreEqual("value2", changing);
645 Assert.AreEqual(null, changed);
646 Assert.AreEqual(null, (string)o["StringValue"]);
647 Assert.AreEqual(3, changingCount);
648 Assert.AreEqual(3, changedCount);
650 o["NullValue"] = null;
651 Assert.AreEqual(null, changing);
652 Assert.AreEqual(null, changed);
653 Assert.AreEqual(new JValue((object)null), o["NullValue"]);
654 Assert.AreEqual(4, changingCount);
655 Assert.AreEqual(4, changedCount);
657 o["NullValue"] = null;
658 Assert.AreEqual(4, changingCount);
659 Assert.AreEqual(4, changedCount);
664 public void PropertyChanged()
666 object changed = null;
667 int changedCount = 0;
669 JObject o = new JObject();
670 o.PropertyChanged += (sender, args) =>
672 JObject s = (JObject)sender;
673 changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
677 o["StringValue"] = "value1";
678 Assert.AreEqual("value1", changed);
679 Assert.AreEqual("value1", (string)o["StringValue"]);
680 Assert.AreEqual(1, changedCount);
682 o["StringValue"] = "value1";
683 Assert.AreEqual(1, changedCount);
685 o["StringValue"] = "value2";
686 Assert.AreEqual("value2", changed);
687 Assert.AreEqual("value2", (string)o["StringValue"]);
688 Assert.AreEqual(2, changedCount);
690 o["StringValue"] = null;
691 Assert.AreEqual(null, changed);
692 Assert.AreEqual(null, (string)o["StringValue"]);
693 Assert.AreEqual(3, changedCount);
695 o["NullValue"] = null;
696 Assert.AreEqual(null, changed);
697 Assert.AreEqual(new JValue((object)null), o["NullValue"]);
698 Assert.AreEqual(4, changedCount);
700 o["NullValue"] = null;
701 Assert.AreEqual(4, changedCount);
705 public void IListContains()
707 JProperty p = new JProperty("Test", 1);
708 IList l = new JObject(p);
710 Assert.IsTrue(l.Contains(p));
711 Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
715 public void IListIndexOf()
717 JProperty p = new JProperty("Test", 1);
718 IList l = new JObject(p);
720 Assert.AreEqual(0, l.IndexOf(p));
721 Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
725 public void IListClear()
727 JProperty p = new JProperty("Test", 1);
728 IList l = new JObject(p);
730 Assert.AreEqual(1, l.Count);
734 Assert.AreEqual(0, l.Count);
738 public void IListCopyTo()
740 JProperty p1 = new JProperty("Test1", 1);
741 JProperty p2 = new JProperty("Test2", "Two");
742 IList l = new JObject(p1, p2);
744 object[] a = new object[l.Count];
748 Assert.AreEqual(p1, a[0]);
749 Assert.AreEqual(p2, a[1]);
753 public void IListAdd()
755 JProperty p1 = new JProperty("Test1", 1);
756 JProperty p2 = new JProperty("Test2", "Two");
757 IList l = new JObject(p1, p2);
759 JProperty p3 = new JProperty("Test3", "III");
763 Assert.AreEqual(3, l.Count);
764 Assert.AreEqual(p3, l[2]);
768 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
769 public void IListAddBadToken()
771 JProperty p1 = new JProperty("Test1", 1);
772 JProperty p2 = new JProperty("Test2", "Two");
773 IList l = new JObject(p1, p2);
775 l.Add(new JValue("Bad!"));
779 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Argument is not a JToken.")]
780 public void IListAddBadValue()
782 JProperty p1 = new JProperty("Test1", 1);
783 JProperty p2 = new JProperty("Test2", "Two");
784 IList l = new JObject(p1, p2);
790 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
791 public void IListAddPropertyWithExistingName()
793 JProperty p1 = new JProperty("Test1", 1);
794 JProperty p2 = new JProperty("Test2", "Two");
795 IList l = new JObject(p1, p2);
797 JProperty p3 = new JProperty("Test2", "II");
803 public void IListRemove()
805 JProperty p1 = new JProperty("Test1", 1);
806 JProperty p2 = new JProperty("Test2", "Two");
807 IList l = new JObject(p1, p2);
809 JProperty p3 = new JProperty("Test3", "III");
813 Assert.AreEqual(2, l.Count);
816 Assert.AreEqual(1, l.Count);
817 Assert.IsFalse(l.Contains(p1));
818 Assert.IsTrue(l.Contains(p2));
821 Assert.AreEqual(0, l.Count);
822 Assert.IsFalse(l.Contains(p2));
823 Assert.AreEqual(null, p2.Parent);
827 public void IListRemoveAt()
829 JProperty p1 = new JProperty("Test1", 1);
830 JProperty p2 = new JProperty("Test2", "Two");
831 IList l = new JObject(p1, p2);
837 Assert.AreEqual(1, l.Count);
840 Assert.AreEqual(0, l.Count);
844 public void IListInsert()
846 JProperty p1 = new JProperty("Test1", 1);
847 JProperty p2 = new JProperty("Test2", "Two");
848 IList l = new JObject(p1, p2);
850 JProperty p3 = new JProperty("Test3", "III");
853 Assert.AreEqual(l, p3.Parent);
855 Assert.AreEqual(p1, l[0]);
856 Assert.AreEqual(p3, l[1]);
857 Assert.AreEqual(p2, l[2]);
861 public void IListIsReadOnly()
863 IList l = new JObject();
864 Assert.IsFalse(l.IsReadOnly);
868 public void IListIsFixedSize()
870 IList l = new JObject();
871 Assert.IsFalse(l.IsFixedSize);
875 public void IListSetItem()
877 JProperty p1 = new JProperty("Test1", 1);
878 JProperty p2 = new JProperty("Test2", "Two");
879 IList l = new JObject(p1, p2);
881 JProperty p3 = new JProperty("Test3", "III");
885 Assert.AreEqual(p3, l[0]);
886 Assert.AreEqual(p2, l[1]);
890 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
891 public void IListSetItemAlreadyExists()
893 JProperty p1 = new JProperty("Test1", 1);
894 JProperty p2 = new JProperty("Test2", "Two");
895 IList l = new JObject(p1, p2);
897 JProperty p3 = new JProperty("Test3", "III");
904 [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
905 public void IListSetItemInvalid()
907 JProperty p1 = new JProperty("Test1", 1);
908 JProperty p2 = new JProperty("Test2", "Two");
909 IList l = new JObject(p1, p2);
911 l[0] = new JValue(true);
915 public void IListSyncRoot()
917 JProperty p1 = new JProperty("Test1", 1);
918 JProperty p2 = new JProperty("Test2", "Two");
919 IList l = new JObject(p1, p2);
921 Assert.IsNotNull(l.SyncRoot);
925 public void IListIsSynchronized()
927 JProperty p1 = new JProperty("Test1", 1);
928 JProperty p2 = new JProperty("Test2", "Two");
929 IList l = new JObject(p1, p2);
931 Assert.IsFalse(l.IsSynchronized);
935 public void GenericListJTokenContains()
937 JProperty p = new JProperty("Test", 1);
938 IList<JToken> l = new JObject(p);
940 Assert.IsTrue(l.Contains(p));
941 Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
945 public void GenericListJTokenIndexOf()
947 JProperty p = new JProperty("Test", 1);
948 IList<JToken> l = new JObject(p);
950 Assert.AreEqual(0, l.IndexOf(p));
951 Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
955 public void GenericListJTokenClear()
957 JProperty p = new JProperty("Test", 1);
958 IList<JToken> l = new JObject(p);
960 Assert.AreEqual(1, l.Count);
964 Assert.AreEqual(0, l.Count);
968 public void GenericListJTokenCopyTo()
970 JProperty p1 = new JProperty("Test1", 1);
971 JProperty p2 = new JProperty("Test2", "Two");
972 IList<JToken> l = new JObject(p1, p2);
974 JToken[] a = new JToken[l.Count];
978 Assert.AreEqual(p1, a[0]);
979 Assert.AreEqual(p2, a[1]);
983 public void GenericListJTokenAdd()
985 JProperty p1 = new JProperty("Test1", 1);
986 JProperty p2 = new JProperty("Test2", "Two");
987 IList<JToken> l = new JObject(p1, p2);
989 JProperty p3 = new JProperty("Test3", "III");
993 Assert.AreEqual(3, l.Count);
994 Assert.AreEqual(p3, l[2]);
998 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
999 public void GenericListJTokenAddBadToken()
1001 JProperty p1 = new JProperty("Test1", 1);
1002 JProperty p2 = new JProperty("Test2", "Two");
1003 IList<JToken> l = new JObject(p1, p2);
1005 l.Add(new JValue("Bad!"));
1009 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
1010 public void GenericListJTokenAddBadValue()
1012 JProperty p1 = new JProperty("Test1", 1);
1013 JProperty p2 = new JProperty("Test2", "Two");
1014 IList<JToken> l = new JObject(p1, p2);
1016 // string is implicitly converted to JValue
1021 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
1022 public void GenericListJTokenAddPropertyWithExistingName()
1024 JProperty p1 = new JProperty("Test1", 1);
1025 JProperty p2 = new JProperty("Test2", "Two");
1026 IList<JToken> l = new JObject(p1, p2);
1028 JProperty p3 = new JProperty("Test2", "II");
1034 public void GenericListJTokenRemove()
1036 JProperty p1 = new JProperty("Test1", 1);
1037 JProperty p2 = new JProperty("Test2", "Two");
1038 IList<JToken> l = new JObject(p1, p2);
1040 JProperty p3 = new JProperty("Test3", "III");
1042 // won't do anything
1043 Assert.IsFalse(l.Remove(p3));
1044 Assert.AreEqual(2, l.Count);
1046 Assert.IsTrue(l.Remove(p1));
1047 Assert.AreEqual(1, l.Count);
1048 Assert.IsFalse(l.Contains(p1));
1049 Assert.IsTrue(l.Contains(p2));
1051 Assert.IsTrue(l.Remove(p2));
1052 Assert.AreEqual(0, l.Count);
1053 Assert.IsFalse(l.Contains(p2));
1054 Assert.AreEqual(null, p2.Parent);
1058 public void GenericListJTokenRemoveAt()
1060 JProperty p1 = new JProperty("Test1", 1);
1061 JProperty p2 = new JProperty("Test2", "Two");
1062 IList<JToken> l = new JObject(p1, p2);
1064 // won't do anything
1068 Assert.AreEqual(1, l.Count);
1071 Assert.AreEqual(0, l.Count);
1075 public void GenericListJTokenInsert()
1077 JProperty p1 = new JProperty("Test1", 1);
1078 JProperty p2 = new JProperty("Test2", "Two");
1079 IList<JToken> l = new JObject(p1, p2);
1081 JProperty p3 = new JProperty("Test3", "III");
1084 Assert.AreEqual(l, p3.Parent);
1086 Assert.AreEqual(p1, l[0]);
1087 Assert.AreEqual(p3, l[1]);
1088 Assert.AreEqual(p2, l[2]);
1092 public void GenericListJTokenIsReadOnly()
1094 IList<JToken> l = new JObject();
1095 Assert.IsFalse(l.IsReadOnly);
1099 public void GenericListJTokenSetItem()
1101 JProperty p1 = new JProperty("Test1", 1);
1102 JProperty p2 = new JProperty("Test2", "Two");
1103 IList<JToken> l = new JObject(p1, p2);
1105 JProperty p3 = new JProperty("Test3", "III");
1109 Assert.AreEqual(p3, l[0]);
1110 Assert.AreEqual(p2, l[1]);
1114 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
1115 public void GenericListJTokenSetItemAlreadyExists()
1117 JProperty p1 = new JProperty("Test1", 1);
1118 JProperty p2 = new JProperty("Test2", "Two");
1119 IList<JToken> l = new JObject(p1, p2);
1121 JProperty p3 = new JProperty("Test3", "III");
1129 public void IBindingListSortDirection()
1131 IBindingList l = new JObject();
1132 Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection);
1136 public void IBindingListSortProperty()
1138 IBindingList l = new JObject();
1139 Assert.AreEqual(null, l.SortProperty);
1143 public void IBindingListSupportsChangeNotification()
1145 IBindingList l = new JObject();
1146 Assert.AreEqual(true, l.SupportsChangeNotification);
1150 public void IBindingListSupportsSearching()
1152 IBindingList l = new JObject();
1153 Assert.AreEqual(false, l.SupportsSearching);
1157 public void IBindingListSupportsSorting()
1159 IBindingList l = new JObject();
1160 Assert.AreEqual(false, l.SupportsSorting);
1164 public void IBindingListAllowEdit()
1166 IBindingList l = new JObject();
1167 Assert.AreEqual(true, l.AllowEdit);
1171 public void IBindingListAllowNew()
1173 IBindingList l = new JObject();
1174 Assert.AreEqual(true, l.AllowNew);
1178 public void IBindingListAllowRemove()
1180 IBindingList l = new JObject();
1181 Assert.AreEqual(true, l.AllowRemove);
1185 public void IBindingListAddIndex()
1187 IBindingList l = new JObject();
1193 [ExpectedException(typeof(NotSupportedException))]
1194 public void IBindingListApplySort()
1196 IBindingList l = new JObject();
1197 l.ApplySort(null, ListSortDirection.Ascending);
1201 [ExpectedException(typeof(NotSupportedException))]
1202 public void IBindingListRemoveSort()
1204 IBindingList l = new JObject();
1209 public void IBindingListRemoveIndex()
1211 IBindingList l = new JObject();
1213 l.RemoveIndex(null);
1217 [ExpectedException(typeof(NotSupportedException))]
1218 public void IBindingListFind()
1220 IBindingList l = new JObject();
1225 public void IBindingListIsSorted()
1227 IBindingList l = new JObject();
1228 Assert.AreEqual(false, l.IsSorted);
1232 [ExpectedException(typeof(Exception), ExpectedMessage = "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.")]
1233 public void IBindingListAddNew()
1235 IBindingList l = new JObject();
1240 public void IBindingListAddNewWithEvent()
1242 JObject o = new JObject();
1243 o.AddingNew += (s, e) => e.NewObject = new JProperty("Property!");
1246 object newObject = l.AddNew();
1247 Assert.IsNotNull(newObject);
1249 JProperty p = (JProperty) newObject;
1250 Assert.AreEqual("Property!", p.Name);
1251 Assert.AreEqual(o, p.Parent);
1255 public void ITypedListGetListName()
1257 JProperty p1 = new JProperty("Test1", 1);
1258 JProperty p2 = new JProperty("Test2", "Two");
1259 ITypedList l = new JObject(p1, p2);
1261 Assert.AreEqual(string.Empty, l.GetListName(null));
1265 public void ITypedListGetItemProperties()
1267 JProperty p1 = new JProperty("Test1", 1);
1268 JProperty p2 = new JProperty("Test2", "Two");
1269 ITypedList l = new JObject(p1, p2);
1271 PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null);
1272 Assert.IsNull(propertyDescriptors);
1276 public void ListChanged()
1278 JProperty p1 = new JProperty("Test1", 1);
1279 JProperty p2 = new JProperty("Test2", "Two");
1280 JObject o = new JObject(p1, p2);
1282 ListChangedType? changedType = null;
1285 o.ListChanged += (s, a) =>
1287 changedType = a.ListChangedType;
1291 JProperty p3 = new JProperty("Test3", "III");
1294 Assert.AreEqual(changedType, ListChangedType.ItemAdded);
1295 Assert.AreEqual(index, 2);
1296 Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
1298 JProperty p4 = new JProperty("Test4", "IV");
1300 ((IList<JToken>) o)[index.Value] = p4;
1301 Assert.AreEqual(changedType, ListChangedType.ItemChanged);
1302 Assert.AreEqual(index, 2);
1303 Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
1304 Assert.IsFalse(((IList<JToken>)o).Contains(p3));
1305 Assert.IsTrue(((IList<JToken>)o).Contains(p4));
1308 Assert.AreEqual(changedType, ListChangedType.ItemChanged);
1309 Assert.AreEqual(index, 0);
1310 Assert.AreEqual(2, (int)o["Test1"]);
1313 #if SILVERLIGHT || !(NET20 || NET35)
1315 public void CollectionChanged()
1317 JProperty p1 = new JProperty("Test1", 1);
1318 JProperty p2 = new JProperty("Test2", "Two");
1319 JObject o = new JObject(p1, p2);
1321 NotifyCollectionChangedAction? changedType = null;
1324 o.CollectionChanged += (s, a) =>
1326 changedType = a.Action;
1327 index = a.NewStartingIndex;
1330 JProperty p3 = new JProperty("Test3", "III");
1333 Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add);
1334 Assert.AreEqual(index, 2);
1335 Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
1337 JProperty p4 = new JProperty("Test4", "IV");
1339 ((IList<JToken>)o)[index.Value] = p4;
1340 Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
1341 Assert.AreEqual(index, 2);
1342 Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
1343 Assert.IsFalse(((IList<JToken>)o).Contains(p3));
1344 Assert.IsTrue(((IList<JToken>)o).Contains(p4));
1347 Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
1348 Assert.AreEqual(index, 0);
1349 Assert.AreEqual(2, (int)o["Test1"]);
1354 public void GetGeocodeAddress()
1357 ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"",
1360 ""request"": ""geocode""
1364 ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"",
1365 ""AddressDetails"": {
1368 ""AdministrativeArea"" : {
1369 ""AdministrativeAreaName"" : ""IL"",
1370 ""SubAdministrativeArea"" : {
1372 ""LocalityName"" : ""Rockford"",
1374 ""PostalCodeNumber"" : ""61107""
1376 ""Thoroughfare"" : {
1377 ""ThoroughfareName"" : ""435 N Mulford Rd""
1380 ""SubAdministrativeAreaName"" : ""Winnebago""
1383 ""CountryName"" : ""USA"",
1384 ""CountryNameCode"" : ""US""
1389 ""north"": 42.2753076,
1390 ""south"": 42.2690124,
1391 ""east"": -88.9964645,
1392 ""west"": -89.0027597
1396 ""coordinates"": [ -88.9995886, 42.2721596, 0 ]
1401 JObject o = JObject.Parse(json);
1403 string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"];
1404 Assert.AreEqual("435 N Mulford Rd", searchAddress);
1408 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Set JObject values with invalid key value: 0. Object property name expected.")]
1409 public void SetValueWithInvalidPropertyName()
1411 JObject o = new JObject();
1412 o[0] = new JValue(3);
1416 public void SetValue()
1418 object key = "TestKey";
1420 JObject o = new JObject();
1421 o[key] = new JValue(3);
1423 Assert.AreEqual(3, (int)o[key]);
1427 public void ParseMultipleProperties()
1430 ""Name"": ""Name1"",
1434 JObject o = JObject.Parse(json);
1435 string value = (string)o["Name"];
1437 Assert.AreEqual("Name2", value);
1441 public void WriteObjectNullDBNullValue()
1443 DBNull dbNull = DBNull.Value;
1444 JValue v = new JValue(dbNull);
1445 Assert.AreEqual(DBNull.Value, v.Value);
1446 Assert.AreEqual(JTokenType.Null, v.Type);
1448 JObject o = new JObject();
1451 string output = o.ToString();
1459 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")]
1460 public void InvalidValueCastExceptionMessage()
1463 ""responseData"": {},
1464 ""responseDetails"": null,
1465 ""responseStatus"": 200
1468 JObject o = JObject.Parse(json);
1470 string name = (string)o["responseData"];
1474 [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")]
1475 public void InvalidPropertyValueCastExceptionMessage()
1478 ""responseData"": {},
1479 ""responseDetails"": null,
1480 ""responseStatus"": 200
1483 JObject o = JObject.Parse(json);
1485 string name = (string)o.Property("responseData");
1489 [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "JSON integer 307953220000517141511 is too large or small for an Int64.")]
1490 public void NumberTooBigForInt64()
1492 string json = @"{""code"": 307953220000517141511}";
1494 JObject.Parse(json);
1498 [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected end of content while loading JObject.")]
1499 public void ParseIncomplete()
1501 JObject.Parse("{ foo:");
1505 public void LoadFromNestedObject()
1507 string jsonText = @"{
1513 ""msg"":""No action taken""
1518 JsonReader reader = new JsonTextReader(new StringReader(jsonText));
1525 JObject o = (JObject)JToken.ReadFrom(reader);
1526 Assert.IsNotNull(o);
1529 ""msg"": ""No action taken""
1530 }", o.ToString(Formatting.Indented));
1534 [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected end of content while loading JObject.")]
1535 public void LoadFromNestedObjectIncomplete()
1537 string jsonText = @"{
1544 JsonReader reader = new JsonTextReader(new StringReader(jsonText));
1551 JToken.ReadFrom(reader);
1556 public void GetProperties()
1558 JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}");
1560 ICustomTypeDescriptor descriptor = o;
1562 PropertyDescriptorCollection properties = descriptor.GetProperties();
1563 Assert.AreEqual(4, properties.Count);
1565 PropertyDescriptor prop1 = properties[0];
1566 Assert.AreEqual("prop1", prop1.Name);
1567 Assert.AreEqual(typeof(long), prop1.PropertyType);
1568 Assert.AreEqual(typeof(JObject), prop1.ComponentType);
1569 Assert.AreEqual(false, prop1.CanResetValue(o));
1570 Assert.AreEqual(false, prop1.ShouldSerializeValue(o));
1572 PropertyDescriptor prop2 = properties[1];
1573 Assert.AreEqual("prop2", prop2.Name);
1574 Assert.AreEqual(typeof(string), prop2.PropertyType);
1575 Assert.AreEqual(typeof(JObject), prop2.ComponentType);
1576 Assert.AreEqual(false, prop2.CanResetValue(o));
1577 Assert.AreEqual(false, prop2.ShouldSerializeValue(o));
1579 PropertyDescriptor prop3 = properties[2];
1580 Assert.AreEqual("prop3", prop3.Name);
1581 Assert.AreEqual(typeof(object), prop3.PropertyType);
1582 Assert.AreEqual(typeof(JObject), prop3.ComponentType);
1583 Assert.AreEqual(false, prop3.CanResetValue(o));
1584 Assert.AreEqual(false, prop3.ShouldSerializeValue(o));
1586 PropertyDescriptor prop4 = properties[3];
1587 Assert.AreEqual("prop4", prop4.Name);
1588 Assert.AreEqual(typeof(JArray), prop4.PropertyType);
1589 Assert.AreEqual(typeof(JObject), prop4.ComponentType);
1590 Assert.AreEqual(false, prop4.CanResetValue(o));
1591 Assert.AreEqual(false, prop4.ShouldSerializeValue(o));