Code Coverage Statistics for Source File
Newtonsoft.Json.Tests\Serialization\JsonSerializerTest.cs
Symbol Coverage: 91.05% (1099 of 1207)
Branch Coverage: 75.18% (209 of 278)
Cyclomatic Complexity Avg: 1.06 Max:4
Code Lines: 1909
Symbol Coverage Trend
View:
L | V | Source |
---|---|---|
1 |
#region License |
|
2 |
// Copyright (c) 2007 James Newton-King |
|
3 |
// |
|
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 |
|
11 |
// conditions: |
|
12 |
// |
|
13 |
// The above copyright notice and this permission notice shall be |
|
14 |
// included in all copies or substantial portions of the Software. |
|
15 |
// |
|
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. |
|
24 |
#endregion |
|
25 |
||
26 |
using System; |
|
27 |
using System.Collections.Generic; |
|
28 |
#if !SILVERLIGHT && !PocketPC && !NET20 |
|
29 |
using System.ComponentModel.DataAnnotations; |
|
30 |
using System.Web.Script.Serialization; |
|
31 |
#endif |
|
32 |
using System.Text; |
|
33 |
using NUnit.Framework; |
|
34 |
using Newtonsoft.Json; |
|
35 |
using System.IO; |
|
36 |
using System.Collections; |
|
37 |
using System.Xml; |
|
38 |
using System.Xml.Serialization; |
|
39 |
using System.Collections.ObjectModel; |
|
40 |
using Newtonsoft.Json.Linq; |
|
41 |
using System.Linq; |
|
42 |
using Newtonsoft.Json.Converters; |
|
43 |
#if !PocketPC && !NET20 |
|
44 |
using System.Runtime.Serialization.Json; |
|
45 |
#endif |
|
46 |
using Newtonsoft.Json.Tests.TestObjects; |
|
47 |
using System.Runtime.Serialization; |
|
48 |
using System.Globalization; |
|
49 |
using Newtonsoft.Json.Utilities; |
|
50 |
using System.Reflection; |
|
51 |
#if !NET20 && !SILVERLIGHT |
|
52 |
using System.Xml.Linq; |
|
53 |
using System.Text.RegularExpressions; |
|
54 |
#endif |
|
55 |
||
56 |
namespace Newtonsoft.Json.Tests.Serialization |
|
57 |
{ |
|
58 |
public class JsonSerializerTest : TestFixtureBase |
|
59 |
{ |
|
60 |
[Test] |
|
61 |
public void PersonTypedObjectDeserialization() |
|
62 |
{ |
|
63 |
1 |
Store store = new Store();
|
64 |
||
65 |
1 |
string jsonText = JsonConvert.SerializeObject(store);
|
66 |
||
67 |
1 |
Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
|
68 |
||
69 |
1 |
Assert.AreEqual(store.Establised, deserializedStore.Establised);
|
70 |
1 |
Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
|
71 |
||
72 |
1 |
Console.WriteLine(jsonText);
|
73 |
1 |
}
|
74 |
||
75 |
[Test] |
|
76 |
public void TypedObjectDeserialization() |
|
77 |
{ |
|
78 |
1 |
Product product = new Product();
|
79 |
||
80 |
1 |
product.Name = "Apple";
|
81 |
1 |
product.ExpiryDate = new DateTime(2008, 12, 28);
|
82 |
1 |
product.Price = 3.99M;
|
83 |
1 |
product.Sizes = new string[] { "Small", "Medium", "Large" };
|
84 |
||
85 |
1 |
string output = JsonConvert.SerializeObject(product);
|
86 |
//{ |
|
87 |
// "Name": "Apple", |
|
88 |
// "ExpiryDate": "\/Date(1230375600000+1300)\/", |
|
89 |
// "Price": 3.99, |
|
90 |
// "Sizes": [ |
|
91 |
// "Small", |
|
92 |
// "Medium", |
|
93 |
// "Large" |
|
94 |
// ] |
|
95 |
//} |
|
96 |
||
97 |
1 |
Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));
|
98 |
||
99 |
1 |
Assert.AreEqual("Apple", deserializedProduct.Name);
|
100 |
1 |
Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
|
101 |
1 |
Assert.AreEqual(3.99, deserializedProduct.Price);
|
102 |
1 |
Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
|
103 |
1 |
Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
|
104 |
1 |
Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
|
105 |
1 |
}
|
106 |
||
107 |
//[Test] |
|
108 |
//public void Advanced() |
|
109 |
//{ |
|
110 |
// Product product = new Product(); |
|
111 |
// product.ExpiryDate = new DateTime(2008, 12, 28); |
|
112 |
||
113 |
// JsonSerializer serializer = new JsonSerializer(); |
|
114 |
// serializer.Converters.Add(new JavaScriptDateTimeConverter()); |
|
115 |
// serializer.NullValueHandling = NullValueHandling.Ignore; |
|
116 |
||
117 |
// using (StreamWriter sw = new StreamWriter(@"c:\json.txt")) |
|
118 |
// using (JsonWriter writer = new JsonTextWriter(sw)) |
|
119 |
// { |
|
120 |
// serializer.Serialize(writer, product); |
|
121 |
// // {"ExpiryDate":new Date(1230375600000),"Price":0} |
|
122 |
// } |
|
123 |
//} |
|
124 |
||
125 |
[Test] |
|
126 |
public void JsonConvertSerializer() |
|
127 |
{ |
|
128 |
1 |
string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
|
129 |
||
130 |
1 |
Product p = JsonConvert.DeserializeObject(value, typeof(Product)) as Product;
|
131 |
||
132 |
1 |
Assert.AreEqual("Orange", p.Name);
|
133 |
1 |
Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
|
134 |
1 |
Assert.AreEqual(3.99, p.Price);
|
135 |
1 |
}
|
136 |
||
137 |
[Test] |
|
138 |
public void DeserializeJavaScriptDate() |
|
139 |
{ |
|
140 |
1 |
DateTime dateValue = new DateTime(2010, 3, 30);
|
141 |
1 |
Dictionary<string, object> testDictionary = new Dictionary<string, object>();
|
142 |
1 |
testDictionary["date"] = dateValue;
|
143 |
||
144 |
1 |
string jsonText = JsonConvert.SerializeObject(testDictionary);
|
145 |
||
146 |
#if !PocketPC && !NET20 |
|
147 |
1 |
MemoryStream ms = new MemoryStream();
|
148 |
1 |
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
|
149 |
1 |
serializer.WriteObject(ms, testDictionary);
|
150 |
||
151 |
1 |
byte[] data = ms.ToArray();
|
152 |
1 |
string output = Encoding.UTF8.GetString(data, 0, data.Length);
|
153 |
#endif |
|
154 |
||
155 |
1 |
Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JsonConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
|
156 |
1 |
DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
|
157 |
||
158 |
1 |
Assert.AreEqual(dateValue, deserializedDate);
|
159 |
||
160 |
1 |
Console.WriteLine("DeserializeJavaScriptDate");
|
161 |
1 |
Console.WriteLine(jsonText);
|
162 |
1 |
Console.WriteLine();
|
163 |
1 |
Console.WriteLine(jsonText);
|
164 |
1 |
}
|
165 |
||
166 |
[Test] |
|
167 |
public void TestMethodExecutorObject() |
|
168 |
{ |
|
169 |
1 |
MethodExecutorObject executorObject = new MethodExecutorObject();
|
170 |
1 |
executorObject.serverClassName = "BanSubs";
|
171 |
1 |
executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
|
172 |
1 |
executorObject.clientGetResultFunction = "ClientBanSubsCB";
|
173 |
||
174 |
1 |
string output = JsonConvert.SerializeObject(executorObject);
|
175 |
||
176 |
1 |
MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
|
177 |
||
178 |
1 |
Assert.AreNotSame(executorObject, executorObject2);
|
179 |
1 |
Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
|
180 |
1 |
Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
|
181 |
1 |
Assert.Contains("101", executorObject2.serverMethodParams);
|
182 |
1 |
Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
|
183 |
1 |
}
|
184 |
||
185 |
#if !SILVERLIGHT |
|
186 |
[Test] |
|
187 |
public void HashtableDeserialization() |
|
188 |
{ |
|
189 |
1 |
string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
|
190 |
||
191 |
1 |
Hashtable p = JsonConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
|
192 |
||
193 |
1 |
Assert.AreEqual("Orange", p["Name"].ToString());
|
194 |
1 |
}
|
195 |
||
196 |
[Test] |
|
197 |
public void TypedHashtableDeserialization() |
|
198 |
{ |
|
199 |
1 |
string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
|
200 |
||
201 |
1 |
TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
|
202 |
||
203 |
1 |
Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
|
204 |
1 |
Assert.AreEqual(@"[
|
205 |
1 |
""01/24/2010 12:00:00""
|
206 |
1 |
]", p.Hash["UntypedArray"].ToString());
|
207 |
1 |
}
|
208 |
#endif |
|
209 |
||
210 |
[Test] |
|
211 |
public void SerializeDeserializeGetOnlyProperty() |
|
212 |
{ |
|
213 |
1 |
string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
|
214 |
||
215 |
1 |
GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
|
216 |
||
217 |
1 |
Assert.AreEqual(c.Field, "Field");
|
218 |
1 |
Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
|
219 |
1 |
}
|
220 |
||
221 |
[Test] |
|
222 |
public void SerializeDeserializeSetOnlyProperty() |
|
223 |
{ |
|
224 |
1 |
string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
|
225 |
||
226 |
1 |
SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
|
227 |
||
228 |
1 |
Assert.AreEqual(c.Field, "Field");
|
229 |
1 |
}
|
230 |
||
231 |
[Test] |
|
232 |
public void JsonIgnoreAttributeTest() |
|
233 |
{ |
|
234 |
1 |
string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
|
235 |
||
236 |
1 |
Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
|
237 |
||
238 |
1 |
JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
|
239 |
||
240 |
1 |
Assert.AreEqual(0, c.IgnoredField);
|
241 |
1 |
Assert.AreEqual(99, c.Field);
|
242 |
1 |
}
|
243 |
||
244 |
[Test] |
|
245 |
public void GoogleSearchAPI() |
|
246 |
{ |
|
247 |
1 |
string json = @"{ |
248 |
1 |
results:
|
249 |
1 |
[
|
250 |
1 |
{
|
251 |
1 |
GsearchResultClass:""GwebSearch"",
|
252 |
1 |
unescapedUrl : ""http://www.google.com/"",
|
253 |
1 |
url : ""http://www.google.com/"",
|
254 |
1 |
visibleUrl : ""www.google.com"",
|
255 |
1 |
cacheUrl :
|
256 |
1 |
""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
|
257 |
1 |
title : ""Google"",
|
258 |
1 |
titleNoFormatting : ""Google"",
|
259 |
1 |
content : ""Enables users to search the Web, Usenet, and
|
260 |
1 |
images. Features include PageRank, caching and translation of
|
261 |
1 |
results, and an option to find similar pages.""
|
262 |
1 |
},
|
263 |
1 |
{
|
264 |
1 |
GsearchResultClass:""GwebSearch"",
|
265 |
1 |
unescapedUrl : ""http://news.google.com/"",
|
266 |
1 |
url : ""http://news.google.com/"",
|
267 |
1 |
visibleUrl : ""news.google.com"",
|
268 |
1 |
cacheUrl :
|
269 |
1 |
""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
|
270 |
1 |
title : ""Google News"",
|
271 |
1 |
titleNoFormatting : ""Google News"",
|
272 |
1 |
content : ""Aggregated headlines and a search engine of many of the world's news sources.""
|
273 |
1 |
},
|
274 |
1 |
|
275 |
1 |
{
|
276 |
1 |
GsearchResultClass:""GwebSearch"",
|
277 |
1 |
unescapedUrl : ""http://groups.google.com/"",
|
278 |
1 |
url : ""http://groups.google.com/"",
|
279 |
1 |
visibleUrl : ""groups.google.com"",
|
280 |
1 |
cacheUrl :
|
281 |
1 |
""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
|
282 |
1 |
title : ""Google Groups"",
|
283 |
1 |
titleNoFormatting : ""Google Groups"",
|
284 |
1 |
content : ""Enables users to search and browse the Usenet
|
285 |
1 |
archives which consist of over 700 million messages, and post new
|
286 |
1 |
comments.""
|
287 |
1 |
},
|
288 |
1 |
|
289 |
1 |
{
|
290 |
1 |
GsearchResultClass:""GwebSearch"",
|
291 |
1 |
unescapedUrl : ""http://maps.google.com/"",
|
292 |
1 |
url : ""http://maps.google.com/"",
|
293 |
1 |
visibleUrl : ""maps.google.com"",
|
294 |
1 |
cacheUrl :
|
295 |
1 |
""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
|
296 |
1 |
title : ""Google Maps"",
|
297 |
1 |
titleNoFormatting : ""Google Maps"",
|
298 |
1 |
content : ""Provides directions, interactive maps, and
|
299 |
1 |
satellite/aerial imagery of the United States. Can also search by
|
300 |
1 |
keyword such as type of business.""
|
301 |
1 |
}
|
302 |
1 |
],
|
303 |
1 |
|
304 |
1 |
adResults:
|
305 |
1 |
[
|
306 |
1 |
{
|
307 |
1 |
GsearchResultClass:""GwebSearch.ad"",
|
308 |
1 |
title : ""Gartner Symposium/ITxpo"",
|
309 |
1 |
content1 : ""Meet brilliant Gartner IT analysts"",
|
310 |
1 |
content2 : ""20-23 May 2007- Barcelona, Spain"",
|
311 |
1 |
url :
|
312 |
1 |
""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="",
|
313 |
1 |
|
314 |
1 |
impressionUrl :
|
315 |
1 |
""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"",
|
316 |
1 |
|
317 |
1 |
unescapedUrl :
|
318 |
1 |
""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="",
|
319 |
1 |
|
320 |
1 |
visibleUrl : ""www.gartner.com""
|
321 |
1 |
}
|
322 |
1 |
]
|
323 |
1 |
}
|
324 |
1 |
";
|
325 |
1 |
object o = JsonConvert.DeserializeObject(json);
|
326 |
1 |
string s = string.Empty;
|
327 |
1 |
s += s;
|
328 |
1 |
}
|
329 |
||
330 |
[Test] |
|
331 |
public void TorrentDeserializeTest() |
|
332 |
{ |
|
333 |
1 |
string jsonText = @"{ |
334 |
1 |
"""":"""",
|
335 |
1 |
""label"": [
|
336 |
1 |
[""SomeName"",6]
|
337 |
1 |
],
|
338 |
1 |
""torrents"": [
|
339 |
1 |
[""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
|
340 |
1 |
],
|
341 |
1 |
""torrentc"": ""1816000723""
|
342 |
1 |
}";
|
343 |
||
344 |
1 |
JObject o = (JObject)JsonConvert.DeserializeObject(jsonText);
|
345 |
1 |
Assert.AreEqual(4, o.Children().Count());
|
346 |
||
347 |
1 |
JToken torrentsArray = (JToken)o["torrents"];
|
348 |
1 |
JToken nestedTorrentsArray = (JToken)torrentsArray[0];
|
349 |
1 |
Assert.AreEqual(nestedTorrentsArray.Children().Count(), 19);
|
350 |
1 |
}
|
351 |
||
352 |
[Test] |
|
353 |
public void JsonPropertyClassSerialize() |
|
354 |
{ |
|
355 |
1 |
JsonPropertyClass test = new JsonPropertyClass();
|
356 |
1 |
test.Pie = "Delicious";
|
357 |
1 |
test.SweetCakesCount = int.MaxValue;
|
358 |
||
359 |
1 |
string jsonText = JsonConvert.SerializeObject(test);
|
360 |
||
361 |
1 |
Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
|
362 |
||
363 |
1 |
JsonPropertyClass test2 = JsonConvert.DeserializeObject<JsonPropertyClass>(jsonText);
|
364 |
||
365 |
1 |
Assert.AreEqual(test.Pie, test2.Pie);
|
366 |
1 |
Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
|
367 |
1 |
}
|
368 |
||
369 |
[Test] |
|
370 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.")] |
|
371 |
public void BadJsonPropertyClassSerialize() |
|
372 |
{ |
|
373 |
1 |
JsonConvert.SerializeObject(new BadJsonPropertyClass());
|
374 |
0 |
}
|
375 |
||
376 |
[Test] |
|
377 |
public void InheritedListSerialize() |
|
378 |
{ |
|
379 |
1 |
Article a1 = new Article("a1");
|
380 |
1 |
Article a2 = new Article("a2");
|
381 |
||
382 |
1 |
ArticleCollection articles1 = new ArticleCollection();
|
383 |
1 |
articles1.Add(a1);
|
384 |
1 |
articles1.Add(a2);
|
385 |
||
386 |
1 |
string jsonText = JsonConvert.SerializeObject(articles1);
|
387 |
||
388 |
1 |
ArticleCollection articles2 = JsonConvert.DeserializeObject<ArticleCollection>(jsonText);
|
389 |
||
390 |
1 |
Assert.AreEqual(articles1.Count, articles2.Count);
|
391 |
1 |
Assert.AreEqual(articles1[0].Name, articles2[0].Name);
|
392 |
1 |
}
|
393 |
||
394 |
[Test] |
|
395 |
public void ReadOnlyCollectionSerialize() |
|
396 |
{ |
|
397 |
1 |
ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(new int[] { 0, 1, 2, 3, 4 });
|
398 |
||
399 |
1 |
string jsonText = JsonConvert.SerializeObject(r1);
|
400 |
||
401 |
1 |
ReadOnlyCollection<int> r2 = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>(jsonText);
|
402 |
||
403 |
1 |
CollectionAssert.AreEqual(r1, r2);
|
404 |
1 |
}
|
405 |
||
406 |
#if !PocketPC && !NET20 |
|
407 |
[Test] |
|
408 |
public void Unicode() |
|
409 |
{ |
|
410 |
1 |
string json = @"[""PRE\u003cPOST""]";
|
411 |
||
412 |
1 |
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
|
413 |
1 |
List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
|
414 |
||
415 |
1 |
List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
|
416 |
||
417 |
1 |
Assert.AreEqual(1, jsonNetResult.Count);
|
418 |
1 |
Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
|
419 |
1 |
}
|
420 |
||
421 |
[Test] |
|
422 |
public void BackslashEqivilence() |
|
423 |
{ |
|
424 |
1 |
string json = @"[""vvv\/vvv\tvvv\""vvv\bvvv\nvvv\rvvv\\vvv\fvvv""]";
|
425 |
||
426 |
#if !SILVERLIGHT |
|
427 |
1 |
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
|
428 |
1 |
List<string> javaScriptSerializerResult = javaScriptSerializer.Deserialize<List<string>>(json);
|
429 |
#endif |
|
430 |
||
431 |
1 |
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
|
432 |
1 |
List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
|
433 |
||
434 |
1 |
List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
|
435 |
||
436 |
1 |
Assert.AreEqual(1, jsonNetResult.Count);
|
437 |
1 |
Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
|
438 |
#if !SILVERLIGHT |
|
439 |
1 |
Assert.AreEqual(javaScriptSerializerResult[0], jsonNetResult[0]);
|
440 |
#endif |
|
441 |
1 |
}
|
442 |
||
443 |
[Test] |
|
444 |
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = @"Bad JSON escape sequence: \j. Line 1, position 7.")] |
|
445 |
public void InvalidBackslash() |
|
446 |
{ |
|
447 |
1 |
string json = @"[""vvv\jvvv""]";
|
448 |
||
449 |
1 |
JsonConvert.DeserializeObject<List<string>>(json);
|
450 |
0 |
}
|
451 |
||
452 |
[Test] |
|
453 |
public void DateTimeTest() |
|
454 |
{ |
|
455 |
1 |
List<DateTime> testDates = new List<DateTime> {
|
456 |
1 |
new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Local),
|
457 |
1 |
new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
|
458 |
1 |
new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc),
|
459 |
1 |
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local),
|
460 |
1 |
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
|
461 |
1 |
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc),
|
462 |
1 |
};
|
463 |
string result; |
|
464 |
||
465 |
||
466 |
1 |
MemoryStream ms = new MemoryStream();
|
467 |
1 |
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<DateTime>));
|
468 |
1 |
s.WriteObject(ms, testDates);
|
469 |
1 |
ms.Seek(0, SeekOrigin.Begin);
|
470 |
1 |
StreamReader sr = new StreamReader(ms);
|
471 |
||
472 |
1 |
string expected = sr.ReadToEnd();
|
473 |
||
474 |
1 |
result = JsonConvert.SerializeObject(testDates);
|
475 |
1 |
Assert.AreEqual(expected, result);
|
476 |
1 |
}
|
477 |
||
478 |
[Test] |
|
479 |
public void DateTimeOffset() |
|
480 |
{ |
|
481 |
1 |
List<DateTimeOffset> testDates = new List<DateTimeOffset> {
|
482 |
1 |
new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
|
483 |
1 |
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
|
484 |
1 |
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
|
485 |
1 |
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
|
486 |
1 |
};
|
487 |
||
488 |
1 |
string result = JsonConvert.SerializeObject(testDates);
|
489 |
1 |
Assert.AreEqual(@"[""\/Date(-59011455539000+0000)\/"",""\/Date(946688461000+0000)\/"",""\/Date(946641661000+1300)\/"",""\/Date(946701061000-0330)\/""]", result);
|
490 |
1 |
}
|
491 |
#endif |
|
492 |
||
493 |
[Test] |
|
494 |
public void NonStringKeyDictionary() |
|
495 |
{ |
|
496 |
1 |
Dictionary<int, int> values = new Dictionary<int, int>();
|
497 |
1 |
values.Add(-5, 6);
|
498 |
1 |
values.Add(int.MinValue, int.MaxValue);
|
499 |
||
500 |
1 |
string json = JsonConvert.SerializeObject(values);
|
501 |
||
502 |
1 |
Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json);
|
503 |
||
504 |
1 |
Dictionary<int, int> newValues = JsonConvert.DeserializeObject<Dictionary<int, int>>(json);
|
505 |
||
506 |
1 |
CollectionAssert.AreEqual(values, newValues);
|
507 |
1 |
}
|
508 |
||
509 |
[Test] |
|
510 |
public void AnonymousObjectSerialization() |
|
511 |
{ |
|
512 |
1 |
var anonymous =
|
513 |
1 |
new
|
514 |
1 |
{
|
515 |
1 |
StringValue = "I am a string",
|
516 |
1 |
IntValue = int.MaxValue,
|
517 |
1 |
NestedAnonymous = new { NestedValue = byte.MaxValue },
|
518 |
1 |
NestedArray = new[] { 1, 2 },
|
519 |
1 |
Product = new Product() { Name = "TestProduct" }
|
520 |
1 |
};
|
521 |
||
522 |
1 |
string json = JsonConvert.SerializeObject(anonymous);
|
523 |
1 |
Assert.AreEqual(@"{""StringValue"":""I am a string"",""IntValue"":2147483647,""NestedAnonymous"":{""NestedValue"":255},""NestedArray"":[1,2],""Product"":{""Name"":""TestProduct"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0,""Sizes"":null}}", json);
|
524 |
||
525 |
1 |
anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);
|
526 |
1 |
Assert.AreEqual("I am a string", anonymous.StringValue);
|
527 |
1 |
Assert.AreEqual(int.MaxValue, anonymous.IntValue);
|
528 |
1 |
Assert.AreEqual(255, anonymous.NestedAnonymous.NestedValue);
|
529 |
1 |
Assert.AreEqual(2, anonymous.NestedArray.Length);
|
530 |
1 |
Assert.AreEqual(1, anonymous.NestedArray[0]);
|
531 |
1 |
Assert.AreEqual(2, anonymous.NestedArray[1]);
|
532 |
1 |
Assert.AreEqual("TestProduct", anonymous.Product.Name);
|
533 |
1 |
}
|
534 |
||
535 |
[Test] |
|
536 |
public void CustomCollectionSerialization() |
|
537 |
{ |
|
538 |
1 |
ProductCollection collection = new ProductCollection()
|
539 |
1 |
{
|
540 |
1 |
new Product() { Name = "Test1" },
|
541 |
1 |
new Product() { Name = "Test2" },
|
542 |
1 |
new Product() { Name = "Test3" }
|
543 |
1 |
};
|
544 |
||
545 |
1 |
JsonSerializer jsonSerializer = new JsonSerializer();
|
546 |
1 |
jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
547 |
||
548 |
1 |
StringWriter sw = new StringWriter();
|
549 |
||
550 |
1 |
jsonSerializer.Serialize(sw, collection);
|
551 |
||
552 |
1 |
Assert.AreEqual(@"[{""Name"":""Test1"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0,""Sizes"":null},{""Name"":""Test2"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0,""Sizes"":null},{""Name"":""Test3"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0,""Sizes"":null}]",
|
553 |
1 |
sw.GetStringBuilder().ToString());
|
554 |
||
555 |
1 |
ProductCollection collectionNew = (ProductCollection)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(sw.GetStringBuilder().ToString())), typeof(ProductCollection));
|
556 |
||
557 |
1 |
CollectionAssert.AreEqual(collection, collectionNew);
|
558 |
1 |
}
|
559 |
||
560 |
[Test] |
|
561 |
public void SerializeObject() |
|
562 |
{ |
|
563 |
1 |
string json = JsonConvert.SerializeObject(new object());
|
564 |
1 |
Assert.AreEqual("{}", json);
|
565 |
1 |
}
|
566 |
||
567 |
[Test] |
|
568 |
public void SerializeNull() |
|
569 |
{ |
|
570 |
1 |
string json = JsonConvert.SerializeObject(null);
|
571 |
1 |
Assert.AreEqual("null", json);
|
572 |
1 |
}
|
573 |
||
574 |
[Test] |
|
575 |
public void CanDeserializeIntArrayWhenNotFirstPropertyInJson() |
|
576 |
{ |
|
577 |
1 |
string json = "{foo:'hello',bar:[1,2,3]}";
|
578 |
1 |
ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
|
579 |
1 |
Assert.AreEqual("hello", wibble.Foo);
|
580 |
||
581 |
1 |
Assert.AreEqual(4, wibble.Bar.Count);
|
582 |
1 |
Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
|
583 |
1 |
Assert.AreEqual(1, wibble.Bar[1]);
|
584 |
1 |
Assert.AreEqual(2, wibble.Bar[2]);
|
585 |
1 |
Assert.AreEqual(3, wibble.Bar[3]);
|
586 |
1 |
}
|
587 |
||
588 |
[Test] |
|
589 |
public void CanDeserializeIntArray_WhenArrayIsFirstPropertyInJson() |
|
590 |
{ |
|
591 |
1 |
string json = "{bar:[1,2,3], foo:'hello'}";
|
592 |
1 |
ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
|
593 |
1 |
Assert.AreEqual("hello", wibble.Foo);
|
594 |
||
595 |
1 |
Assert.AreEqual(4, wibble.Bar.Count);
|
596 |
1 |
Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
|
597 |
1 |
Assert.AreEqual(1, wibble.Bar[1]);
|
598 |
1 |
Assert.AreEqual(2, wibble.Bar[2]);
|
599 |
1 |
Assert.AreEqual(3, wibble.Bar[3]);
|
600 |
1 |
}
|
601 |
||
602 |
[Test] |
|
603 |
public void ObjectCreationHandlingReplace() |
|
604 |
{ |
|
605 |
1 |
string json = "{bar:[1,2,3], foo:'hello'}";
|
606 |
||
607 |
1 |
JsonSerializer s = new JsonSerializer();
|
608 |
1 |
s.ObjectCreationHandling = ObjectCreationHandling.Replace;
|
609 |
||
610 |
1 |
ClassWithArray wibble = (ClassWithArray)s.Deserialize(new StringReader(json), typeof(ClassWithArray));
|
611 |
||
612 |
1 |
Assert.AreEqual("hello", wibble.Foo);
|
613 |
||
614 |
1 |
Assert.AreEqual(1, wibble.Bar.Count);
|
615 |
1 |
}
|
616 |
||
617 |
[Test] |
|
618 |
public void CanDeserializeSerializedJson() |
|
619 |
{ |
|
620 |
1 |
ClassWithArray wibble = new ClassWithArray();
|
621 |
1 |
wibble.Foo = "hello";
|
622 |
1 |
wibble.Bar.Add(1);
|
623 |
1 |
wibble.Bar.Add(2);
|
624 |
1 |
wibble.Bar.Add(3);
|
625 |
1 |
string json = JsonConvert.SerializeObject(wibble);
|
626 |
||
627 |
1 |
ClassWithArray wibbleOut = JsonConvert.DeserializeObject<ClassWithArray>(json);
|
628 |
1 |
Assert.AreEqual("hello", wibbleOut.Foo);
|
629 |
||
630 |
1 |
Assert.AreEqual(5, wibbleOut.Bar.Count);
|
631 |
1 |
Assert.AreEqual(int.MaxValue, wibbleOut.Bar[0]);
|
632 |
1 |
Assert.AreEqual(int.MaxValue, wibbleOut.Bar[1]);
|
633 |
1 |
Assert.AreEqual(1, wibbleOut.Bar[2]);
|
634 |
1 |
Assert.AreEqual(2, wibbleOut.Bar[3]);
|
635 |
1 |
Assert.AreEqual(3, wibbleOut.Bar[4]);
|
636 |
1 |
}
|
637 |
||
638 |
[Test] |
|
639 |
public void SerializeConverableObjects() |
|
640 |
{ |
|
641 |
1 |
string json = JsonConvert.SerializeObject(new ConverableMembers());
|
642 |
||
643 |
1 |
Assert.AreEqual(@"{""String"":""string"",""Int32"":2147483647,""UInt32"":4294967295,""Byte"":255,""SByte"":127,""Short"":32767,""UShort"":65535,""Long"":9223372036854775807,""ULong"":9223372036854775807,""Double"":1.7976931348623157E+308,""Float"":3.40282347E+38,""DBNull"":null,""Bool"":true,""Char"":""\u0000""}", json);
|
644 |
||
645 |
1 |
ConverableMembers c = JsonConvert.DeserializeObject<ConverableMembers>(json);
|
646 |
1 |
Assert.AreEqual("string", c.String);
|
647 |
1 |
Assert.AreEqual(double.MaxValue, c.Double);
|
648 |
1 |
Assert.AreEqual(DBNull.Value, c.DBNull);
|
649 |
1 |
}
|
650 |
||
651 |
[Test] |
|
652 |
public void SerializeStack() |
|
653 |
{ |
|
654 |
1 |
Stack<object> s = new Stack<object>();
|
655 |
1 |
s.Push(1);
|
656 |
1 |
s.Push(2);
|
657 |
1 |
s.Push(3);
|
658 |
||
659 |
1 |
string json = JsonConvert.SerializeObject(s);
|
660 |
1 |
Assert.AreEqual("[3,2,1]", json);
|
661 |
1 |
}
|
662 |
||
663 |
[Test] |
|
664 |
public void GuidTest() |
|
665 |
{ |
|
666 |
1 |
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
|
667 |
||
668 |
1 |
string json = JsonConvert.SerializeObject(new ClassWithGuid { GuidField = guid });
|
669 |
1 |
Assert.AreEqual(@"{""GuidField"":""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""}", json);
|
670 |
||
671 |
1 |
ClassWithGuid c = JsonConvert.DeserializeObject<ClassWithGuid>(json);
|
672 |
1 |
Assert.AreEqual(guid, c.GuidField);
|
673 |
1 |
}
|
674 |
||
675 |
[Test] |
|
676 |
public void EnumTest() |
|
677 |
{ |
|
678 |
1 |
string json = JsonConvert.SerializeObject(StringComparison.CurrentCultureIgnoreCase);
|
679 |
1 |
Assert.AreEqual(@"1", json);
|
680 |
||
681 |
1 |
StringComparison s = JsonConvert.DeserializeObject<StringComparison>(json);
|
682 |
1 |
Assert.AreEqual(StringComparison.CurrentCultureIgnoreCase, s);
|
683 |
1 |
}
|
684 |
||
685 |
public class ClassWithTimeSpan |
|
686 |
{ |
|
687 |
public TimeSpan TimeSpanField; |
|
688 |
} |
|
689 |
||
690 |
[Test] |
|
691 |
public void TimeSpanTest() |
|
692 |
{ |
|
693 |
1 |
TimeSpan ts = new TimeSpan(00, 23, 59, 1);
|
694 |
||
695 |
1 |
string json = JsonConvert.SerializeObject(new ClassWithTimeSpan { TimeSpanField = ts }, Formatting.Indented);
|
696 |
1 |
Assert.AreEqual(@"{
|
697 |
1 |
""TimeSpanField"": ""23:59:01""
|
698 |
1 |
}", json);
|
699 |
||
700 |
1 |
ClassWithTimeSpan c = JsonConvert.DeserializeObject<ClassWithTimeSpan>(json);
|
701 |
1 |
Assert.AreEqual(ts, c.TimeSpanField);
|
702 |
1 |
}
|
703 |
||
704 |
[Test] |
|
705 |
public void JsonIgnoreAttributeOnClassTest() |
|
706 |
{ |
|
707 |
1 |
string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeOnClassTestClass());
|
708 |
||
709 |
1 |
Assert.AreEqual(@"{""TheField"":0,""Property"":21}", json);
|
710 |
||
711 |
1 |
JsonIgnoreAttributeOnClassTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeOnClassTestClass>(@"{""TheField"":99,""Property"":-1,""IgnoredField"":-1}");
|
712 |
||
713 |
1 |
Assert.AreEqual(0, c.IgnoredField);
|
714 |
1 |
Assert.AreEqual(99, c.Field);
|
715 |
1 |
}
|
716 |
||
717 |
#if !SILVERLIGHT |
|
718 |
[Test] |
|
719 |
public void SerializeArrayAsArrayList() |
|
720 |
{ |
|
721 |
1 |
string jsonText = @"[3, ""somestring"",[1,2,3],{}]";
|
722 |
1 |
ArrayList o = JsonConvert.DeserializeObject<ArrayList>(jsonText);
|
723 |
||
724 |
1 |
Assert.AreEqual(4, o.Count);
|
725 |
1 |
Assert.AreEqual(3, ((JArray)o[2]).Count);
|
726 |
1 |
Assert.AreEqual(0, ((JObject)o[3]).Count);
|
727 |
1 |
}
|
728 |
#endif |
|
729 |
||
730 |
[Test] |
|
731 |
public void SerializeMemberGenericList() |
|
732 |
{ |
|
733 |
1 |
Name name = new Name("The Idiot in Next To Me");
|
734 |
||
735 |
1 |
PhoneNumber p1 = new PhoneNumber("555-1212");
|
736 |
1 |
PhoneNumber p2 = new PhoneNumber("444-1212");
|
737 |
||
738 |
1 |
name.pNumbers.Add(p1);
|
739 |
1 |
name.pNumbers.Add(p2);
|
740 |
||
741 |
1 |
string json = JsonConvert.SerializeObject(name, Formatting.Indented);
|
742 |
||
743 |
1 |
Assert.AreEqual(@"{
|
744 |
1 |
""personsName"": ""The Idiot in Next To Me"",
|
745 |
1 |
""pNumbers"": [
|
746 |
1 |
{
|
747 |
1 |
""phoneNumber"": ""555-1212""
|
748 |
1 |
},
|
749 |
1 |
{
|
750 |
1 |
""phoneNumber"": ""444-1212""
|
751 |
1 |
}
|
752 |
1 |
]
|
753 |
1 |
}", json);
|
754 |
||
755 |
1 |
Name newName = JsonConvert.DeserializeObject<Name>(json);
|
756 |
||
757 |
1 |
Assert.AreEqual("The Idiot in Next To Me", newName.personsName);
|
758 |
||
759 |
// not passed in as part of the constructor but assigned to pNumbers property |
|
760 |
1 |
Assert.AreEqual(2, newName.pNumbers.Count);
|
761 |
1 |
Assert.AreEqual("555-1212", newName.pNumbers[0].phoneNumber);
|
762 |
1 |
Assert.AreEqual("444-1212", newName.pNumbers[1].phoneNumber);
|
763 |
1 |
}
|
764 |
||
765 |
[Test] |
|
766 |
public void ConstructorCaseSensitivity() |
|
767 |
{ |
|
768 |
1 |
ConstructorCaseSensitivityClass c = new ConstructorCaseSensitivityClass("param1", "Param1", "Param2");
|
769 |
||
770 |
1 |
string json = JsonConvert.SerializeObject(c);
|
771 |
||
772 |
1 |
ConstructorCaseSensitivityClass deserialized = JsonConvert.DeserializeObject<ConstructorCaseSensitivityClass>(json);
|
773 |
||
774 |
1 |
Assert.AreEqual("param1", deserialized.param1);
|
775 |
1 |
Assert.AreEqual("Param1", deserialized.Param1);
|
776 |
1 |
Assert.AreEqual("Param2", deserialized.Param2);
|
777 |
1 |
}
|
778 |
||
779 |
[Test] |
|
780 |
public void SerializerShouldUseClassConverter() |
|
781 |
{ |
|
782 |
1 |
ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
|
783 |
||
784 |
1 |
string json = JsonConvert.SerializeObject(c1);
|
785 |
1 |
Assert.AreEqual(@"[""Class"",""!Test!""]", json);
|
786 |
||
787 |
1 |
ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json);
|
788 |
||
789 |
1 |
Assert.AreEqual("!Test!", c2.TestValue);
|
790 |
1 |
}
|
791 |
||
792 |
[Test] |
|
793 |
public void SerializerShouldUseClassConverterOverArgumentConverter() |
|
794 |
{ |
|
795 |
1 |
ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
|
796 |
||
797 |
1 |
string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
|
798 |
1 |
Assert.AreEqual(@"[""Class"",""!Test!""]", json);
|
799 |
||
800 |
1 |
ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json, new ArgumentConverterPrecedenceClassConverter());
|
801 |
||
802 |
1 |
Assert.AreEqual("!Test!", c2.TestValue);
|
803 |
1 |
}
|
804 |
||
805 |
[Test] |
|
806 |
public void SerializerShouldUseMemberConverter() |
|
807 |
{ |
|
808 |
1 |
DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
|
809 |
1 |
MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
|
810 |
||
811 |
1 |
string json = JsonConvert.SerializeObject(m1);
|
812 |
1 |
Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
|
813 |
||
814 |
1 |
MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
|
815 |
||
816 |
1 |
Assert.AreEqual(testDate, m2.DefaultConverter);
|
817 |
1 |
Assert.AreEqual(testDate, m2.MemberConverter);
|
818 |
1 |
}
|
819 |
||
820 |
[Test] |
|
821 |
public void SerializerShouldUseMemberConverterOverArgumentConverter() |
|
822 |
{ |
|
823 |
1 |
DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
|
824 |
1 |
MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
|
825 |
||
826 |
1 |
string json = JsonConvert.SerializeObject(m1, new JavaScriptDateTimeConverter());
|
827 |
1 |
Assert.AreEqual(@"{""DefaultConverter"":new Date(0),""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
|
828 |
||
829 |
1 |
MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JavaScriptDateTimeConverter());
|
830 |
||
831 |
1 |
Assert.AreEqual(testDate, m2.DefaultConverter);
|
832 |
1 |
Assert.AreEqual(testDate, m2.MemberConverter);
|
833 |
1 |
}
|
834 |
||
835 |
[Test] |
|
836 |
public void ConverterAttributeExample() |
|
837 |
{ |
|
838 |
1 |
DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
|
839 |
||
840 |
1 |
MemberConverterClass c = new MemberConverterClass
|
841 |
1 |
{
|
842 |
1 |
DefaultConverter = date,
|
843 |
1 |
MemberConverter = date
|
844 |
1 |
};
|
845 |
||
846 |
1 |
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
|
847 |
||
848 |
1 |
Console.WriteLine(json);
|
849 |
//{ |
|
850 |
// "DefaultConverter": "\/Date(0)\/", |
|
851 |
// "MemberConverter": "1970-01-01T00:00:00Z" |
|
852 |
//} |
|
853 |
1 |
}
|
854 |
||
855 |
[Test] |
|
856 |
public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter() |
|
857 |
{ |
|
858 |
1 |
ClassAndMemberConverterClass c1 = new ClassAndMemberConverterClass();
|
859 |
1 |
c1.DefaultConverter = new ConverterPrecedenceClass("DefaultConverterValue");
|
860 |
1 |
c1.MemberConverter = new ConverterPrecedenceClass("MemberConverterValue");
|
861 |
||
862 |
1 |
string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
|
863 |
1 |
Assert.AreEqual(@"{""DefaultConverter"":[""Class"",""DefaultConverterValue""],""MemberConverter"":[""Member"",""MemberConverterValue""]}", json);
|
864 |
||
865 |
1 |
ClassAndMemberConverterClass c2 = JsonConvert.DeserializeObject<ClassAndMemberConverterClass>(json, new ArgumentConverterPrecedenceClassConverter());
|
866 |
||
867 |
1 |
Assert.AreEqual("DefaultConverterValue", c2.DefaultConverter.TestValue);
|
868 |
1 |
Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
|
869 |
1 |
}
|
870 |
||
871 |
[Test] |
|
872 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JsonConverter IsoDateTimeConverter on Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass is not compatible with member type IncompatibleJsonAttributeClass.")] |
|
873 |
public void IncompatibleJsonAttributeShouldThrow() |
|
874 |
{ |
|
875 |
1 |
IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
|
876 |
1 |
JsonConvert.SerializeObject(c);
|
877 |
0 |
}
|
878 |
||
879 |
[Test] |
|
880 |
public void GenericAbstractProperty() |
|
881 |
{ |
|
882 |
1 |
string json = JsonConvert.SerializeObject(new GenericImpl());
|
883 |
1 |
Assert.AreEqual(@"{""Id"":0}", json);
|
884 |
1 |
}
|
885 |
||
886 |
[Test] |
|
887 |
public void DeserializeNullable() |
|
888 |
{ |
|
889 |
string json; |
|
890 |
||
891 |
1 |
json = JsonConvert.SerializeObject((int?)null);
|
892 |
1 |
Assert.AreEqual("null", json);
|
893 |
||
894 |
1 |
json = JsonConvert.SerializeObject((int?)1);
|
895 |
1 |
Assert.AreEqual("1", json);
|
896 |
1 |
}
|
897 |
||
898 |
[Test] |
|
899 |
public void SerializeJsonRaw() |
|
900 |
{ |
|
901 |
1 |
PersonRaw personRaw = new PersonRaw
|
902 |
1 |
{
|
903 |
1 |
FirstName = "FirstNameValue",
|
904 |
1 |
RawContent = new JRaw("[1,2,3,4,5]"),
|
905 |
1 |
LastName = "LastNameValue"
|
906 |
1 |
};
|
907 |
||
908 |
string json; |
|
909 |
||
910 |
1 |
json = JsonConvert.SerializeObject(personRaw);
|
911 |
1 |
Assert.AreEqual(@"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}", json);
|
912 |
1 |
}
|
913 |
||
914 |
[Test] |
|
915 |
public void DeserializeJsonRaw() |
|
916 |
{ |
|
917 |
1 |
string json = @"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}";
|
918 |
||
919 |
1 |
PersonRaw personRaw = JsonConvert.DeserializeObject<PersonRaw>(json);
|
920 |
||
921 |
1 |
Assert.AreEqual("FirstNameValue", personRaw.FirstName);
|
922 |
1 |
Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.ToString());
|
923 |
1 |
Assert.AreEqual("LastNameValue", personRaw.LastName);
|
924 |
1 |
}
|
925 |
||
926 |
||
927 |
[Test] |
|
928 |
public void DeserializeNullableMember() |
|
929 |
{ |
|
930 |
1 |
UserNullable userNullablle = new UserNullable
|
931 |
1 |
{
|
932 |
1 |
Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
|
933 |
1 |
FName = "FirstValue",
|
934 |
1 |
LName = "LastValue",
|
935 |
1 |
RoleId = 5,
|
936 |
1 |
NullableRoleId = 6,
|
937 |
1 |
NullRoleId = null,
|
938 |
1 |
Active = true
|
939 |
1 |
};
|
940 |
||
941 |
1 |
string json = JsonConvert.SerializeObject(userNullablle);
|
942 |
||
943 |
1 |
Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
|
944 |
||
945 |
1 |
UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
|
946 |
||
947 |
1 |
Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
|
948 |
1 |
Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
|
949 |
1 |
Assert.AreEqual("LastValue", userNullablleDeserialized.LName);
|
950 |
1 |
Assert.AreEqual(5, userNullablleDeserialized.RoleId);
|
951 |
1 |
Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId);
|
952 |
1 |
Assert.AreEqual(null, userNullablleDeserialized.NullRoleId);
|
953 |
1 |
Assert.AreEqual(true, userNullablleDeserialized.Active);
|
954 |
1 |
}
|
955 |
||
956 |
[Test] |
|
957 |
public void DeserializeInt64ToNullableDouble() |
|
958 |
{ |
|
959 |
1 |
string json = @"{""Height"":1}";
|
960 |
||
961 |
1 |
DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
|
962 |
1 |
Assert.AreEqual(1, c.Height);
|
963 |
1 |
}
|
964 |
||
965 |
[Test] |
|
966 |
public void SerializeTypeProperty() |
|
967 |
{ |
|
968 |
1 |
string boolRef = typeof(bool).AssemblyQualifiedName;
|
969 |
1 |
TypeClass typeClass = new TypeClass { TypeProperty = typeof(bool) };
|
970 |
||
971 |
1 |
string json = JsonConvert.SerializeObject(typeClass);
|
972 |
1 |
Assert.AreEqual(@"{""TypeProperty"":""" + boolRef + @"""}", json);
|
973 |
||
974 |
1 |
TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
|
975 |
1 |
Assert.AreEqual(typeof(bool), typeClass2.TypeProperty);
|
976 |
||
977 |
1 |
string jsonSerializerTestRef = typeof(JsonSerializerTest).AssemblyQualifiedName;
|
978 |
1 |
typeClass = new TypeClass { TypeProperty = typeof(JsonSerializerTest) };
|
979 |
||
980 |
1 |
json = JsonConvert.SerializeObject(typeClass);
|
981 |
1 |
Assert.AreEqual(@"{""TypeProperty"":""" + jsonSerializerTestRef + @"""}", json);
|
982 |
||
983 |
1 |
typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
|
984 |
1 |
Assert.AreEqual(typeof(JsonSerializerTest), typeClass2.TypeProperty);
|
985 |
1 |
}
|
986 |
||
987 |
[Test] |
|
988 |
public void RequiredMembersClass() |
|
989 |
{ |
|
990 |
1 |
RequiredMembersClass c = new RequiredMembersClass()
|
991 |
1 |
{
|
992 |
1 |
BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
|
993 |
1 |
FirstName = "Bob",
|
994 |
1 |
LastName = "Smith",
|
995 |
1 |
MiddleName = "Cosmo"
|
996 |
1 |
};
|
997 |
||
998 |
1 |
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
|
999 |
||
1000 |
1 |
Assert.AreEqual(@"{
|
1001 |
1 |
""FirstName"": ""Bob"",
|
1002 |
1 |
""MiddleName"": ""Cosmo"",
|
1003 |
1 |
""LastName"": ""Smith"",
|
1004 |
1 |
""BirthDate"": ""\/Date(977309755000)\/""
|
1005 |
1 |
}", json);
|
1006 |
||
1007 |
1 |
RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
|
1008 |
||
1009 |
1 |
Assert.AreEqual("Bob", c2.FirstName);
|
1010 |
1 |
Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
|
1011 |
1 |
}
|
1012 |
||
1013 |
[Test] |
|
1014 |
public void RequiredMembersClassWithNullValues() |
|
1015 |
{ |
|
1016 |
1 |
string json = @"{ |
1017 |
1 |
""FirstName"": ""I can't be null bro!"",
|
1018 |
1 |
""MiddleName"": null,
|
1019 |
1 |
""LastName"": null,
|
1020 |
1 |
""BirthDate"": ""\/Date(977309755000)\/""
|
1021 |
1 |
}";
|
1022 |
||
1023 |
1 |
RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
|
1024 |
||
1025 |
1 |
Assert.AreEqual("I can't be null bro!", c.FirstName);
|
1026 |
1 |
Assert.AreEqual(null, c.MiddleName);
|
1027 |
1 |
Assert.AreEqual(null, c.LastName);
|
1028 |
1 |
}
|
1029 |
||
1030 |
[Test] |
|
1031 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Required property 'FirstName' expects a value but got null.")] |
|
1032 |
public void RequiredMembersClassNullRequiredValueProperty() |
|
1033 |
{ |
|
1034 |
1 |
string json = @"{ |
1035 |
1 |
""FirstName"": null,
|
1036 |
1 |
""MiddleName"": null,
|
1037 |
1 |
""LastName"": null,
|
1038 |
1 |
""BirthDate"": ""\/Date(977309755000)\/""
|
1039 |
1 |
}";
|
1040 |
||
1041 |
1 |
JsonConvert.DeserializeObject<RequiredMembersClass>(json);
|
1042 |
0 |
}
|
1043 |
||
1044 |
[Test] |
|
1045 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Required property 'LastName' not found in JSON.")] |
|
1046 |
public void RequiredMembersClassMissingRequiredProperty() |
|
1047 |
{ |
|
1048 |
1 |
string json = @"{ |
1049 |
1 |
""FirstName"": ""Bob""
|
1050 |
1 |
}";
|
1051 |
||
1052 |
1 |
JsonConvert.DeserializeObject<RequiredMembersClass>(json);
|
1053 |
0 |
}
|
1054 |
||
1055 |
[Test] |
|
1056 |
public void SerializeJaggedArray() |
|
1057 |
{ |
|
1058 |
1 |
JaggedArray aa = new JaggedArray();
|
1059 |
1 |
aa.Before = "Before!";
|
1060 |
1 |
aa.After = "After!";
|
1061 |
1 |
aa.Coordinates = new[] { new[] { 1, 1 }, new[] { 1, 2 }, new[] { 2, 1 }, new[] { 2, 2 } };
|
1062 |
||
1063 |
1 |
string json = JsonConvert.SerializeObject(aa);
|
1064 |
||
1065 |
1 |
Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
|
1066 |
1 |
}
|
1067 |
||
1068 |
[Test] |
|
1069 |
public void DeserializeJaggedArray() |
|
1070 |
{ |
|
1071 |
1 |
string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
|
1072 |
||
1073 |
1 |
JaggedArray aa = JsonConvert.DeserializeObject<JaggedArray>(json);
|
1074 |
||
1075 |
1 |
Assert.AreEqual("Before!", aa.Before);
|
1076 |
1 |
Assert.AreEqual("After!", aa.After);
|
1077 |
1 |
Assert.AreEqual(4, aa.Coordinates.Length);
|
1078 |
1 |
Assert.AreEqual(2, aa.Coordinates[0].Length);
|
1079 |
1 |
Assert.AreEqual(1, aa.Coordinates[0][0]);
|
1080 |
1 |
Assert.AreEqual(2, aa.Coordinates[1][1]);
|
1081 |
||
1082 |
1 |
string after = JsonConvert.SerializeObject(aa);
|
1083 |
||
1084 |
1 |
Assert.AreEqual(json, after);
|
1085 |
1 |
}
|
1086 |
||
1087 |
[Test] |
|
1088 |
public void DeserializeGoogleGeoCode() |
|
1089 |
{ |
|
1090 |
1 |
string json = @"{ |
1091 |
1 |
""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
|
1092 |
1 |
""Status"": {
|
1093 |
1 |
""code"": 200,
|
1094 |
1 |
""request"": ""geocode""
|
1095 |
1 |
},
|
1096 |
1 |
""Placemark"": [
|
1097 |
1 |
{
|
1098 |
1 |
""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
|
1099 |
1 |
""AddressDetails"": {
|
1100 |
1 |
""Country"": {
|
1101 |
1 |
""CountryNameCode"": ""US"",
|
1102 |
1 |
""AdministrativeArea"": {
|
1103 |
1 |
""AdministrativeAreaName"": ""CA"",
|
1104 |
1 |
""SubAdministrativeArea"": {
|
1105 |
1 |
""SubAdministrativeAreaName"": ""Santa Clara"",
|
1106 |
1 |
""Locality"": {
|
1107 |
1 |
""LocalityName"": ""Mountain View"",
|
1108 |
1 |
""Thoroughfare"": {
|
1109 |
1 |
""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
|
1110 |
1 |
},
|
1111 |
1 |
""PostalCode"": {
|
1112 |
1 |
""PostalCodeNumber"": ""94043""
|
1113 |
1 |
}
|
1114 |
1 |
}
|
1115 |
1 |
}
|
1116 |
1 |
}
|
1117 |
1 |
},
|
1118 |
1 |
""Accuracy"": 8
|
1119 |
1 |
},
|
1120 |
1 |
""Point"": {
|
1121 |
1 |
""coordinates"": [-122.083739, 37.423021, 0]
|
1122 |
1 |
}
|
1123 |
1 |
}
|
1124 |
1 |
]
|
1125 |
1 |
}";
|
1126 |
||
1127 |
1 |
GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
|
1128 |
1 |
}
|
1129 |
||
1130 |
[Test] |
|
1131 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated.")] |
|
1132 |
public void DeserializeInterfaceProperty() |
|
1133 |
{ |
|
1134 |
1 |
InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
|
1135 |
1 |
testClass.co = new Co();
|
1136 |
1 |
String strFromTest = JsonConvert.SerializeObject(testClass);
|
1137 |
1 |
InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass)JsonConvert.DeserializeObject(strFromTest, typeof(InterfacePropertyTestClass));
|
1138 |
0 |
}
|
1139 |
||
1140 |
private Person GetPerson() |
|
1141 |
{ |
|
1142 |
0 |
Person person = new Person
|
1143 |
0 |
{
|
1144 |
0 |
Name = "Mike Manager",
|
1145 |
0 |
BirthDate = new DateTime(1983, 8, 3, 0, 0, 0, DateTimeKind.Utc),
|
1146 |
0 |
Department = "IT",
|
1147 |
0 |
LastModified = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)
|
1148 |
0 |
};
|
1149 |
0 |
return person;
|
1150 |
0 |
}
|
1151 |
||
1152 |
//[Test] |
|
1153 |
public void WriteJsonToFile() |
|
1154 |
{ |
|
1155 |
//Person person = GetPerson(); |
|
1156 |
||
1157 |
//string json = JsonConvert.SerializeObject(person, Formatting.Indented); |
|
1158 |
||
1159 |
//File.WriteAllText(@"c:\person.json", json); |
|
1160 |
||
1161 |
0 |
Person person = GetPerson();
|
1162 |
||
1163 |
0 |
using (FileStream fs = System.IO.File.Open(@"c:\person.json", FileMode.CreateNew))
|
1164 |
0 |
using (StreamWriter sw = new StreamWriter(fs))
|
1165 |
0 |
using (JsonWriter jw = new JsonTextWriter(sw))
|
1166 |
{ |
|
1167 |
0 |
jw.Formatting = Formatting.Indented;
|
1168 |
||
1169 |
0 |
JsonSerializer serializer = new JsonSerializer();
|
1170 |
0 |
serializer.Serialize(jw, person);
|
1171 |
} |
|
1172 |
0 |
}
|
1173 |
||
1174 |
[Test] |
|
1175 |
public void WriteJsonDates() |
|
1176 |
{ |
|
1177 |
1 |
LogEntry entry = new LogEntry
|
1178 |
1 |
{
|
1179 |
1 |
LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
|
1180 |
1 |
Details = "Application started."
|
1181 |
1 |
};
|
1182 |
||
1183 |
1 |
string defaultJson = JsonConvert.SerializeObject(entry);
|
1184 |
// {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"} |
|
1185 |
||
1186 |
1 |
string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
|
1187 |
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00.0000000Z"} |
|
1188 |
||
1189 |
1 |
string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
|
1190 |
// {"Details":"Application started.","LogDate":new Date(1234656000000)} |
|
1191 |
||
1192 |
1 |
Console.WriteLine(defaultJson);
|
1193 |
1 |
Console.WriteLine(isoJson);
|
1194 |
1 |
Console.WriteLine(javascriptJson);
|
1195 |
1 |
}
|
1196 |
||
1197 |
public void GenericListAndDictionaryInterfaceProperties() |
|
1198 |
{ |
|
1199 |
0 |
GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
|
1200 |
0 |
o.IDictionaryProperty = new Dictionary<string, int>
|
1201 |
0 |
{
|
1202 |
0 |
{"one", 1},
|
1203 |
0 |
{"two", 2},
|
1204 |
0 |
{"three", 3}
|
1205 |
0 |
};
|
1206 |
0 |
o.IListProperty = new List<int>
|
1207 |
0 |
{
|
1208 |
0 |
1, 2, 3
|
1209 |
0 |
};
|
1210 |
0 |
o.IEnumerableProperty = new List<int>
|
1211 |
0 |
{
|
1212 |
0 |
4, 5, 6
|
1213 |
0 |
};
|
1214 |
||
1215 |
0 |
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
|
1216 |
||
1217 |
0 |
Assert.AreEqual(@"{
|
1218 |
0 |
""IEnumerableProperty"": [
|
1219 |
0 |
4,
|
1220 |
0 |
5,
|
1221 |
0 |
6
|
1222 |
0 |
],
|
1223 |
0 |
""IListProperty"": [
|
1224 |
0 |
1,
|
1225 |
0 |
2,
|
1226 |
0 |
3
|
1227 |
0 |
],
|
1228 |
0 |
""IDictionaryProperty"": {
|
1229 |
0 |
""one"": 1,
|
1230 |
0 |
""two"": 2,
|
1231 |
0 |
""three"": 3
|
1232 |
0 |
}
|
1233 |
0 |
}", json);
|
1234 |
||
1235 |
0 |
GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
|
1236 |
0 |
Assert.IsNotNull(deserializedObject);
|
1237 |
||
1238 |
0 |
CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
|
1239 |
0 |
CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
|
1240 |
0 |
CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
|
1241 |
0 |
}
|
1242 |
||
1243 |
[Test] |
|
1244 |
public void DeserializeBestMatchPropertyCase() |
|
1245 |
{ |
|
1246 |
1 |
string json = @"{ |
1247 |
1 |
""firstName"": ""firstName"",
|
1248 |
1 |
""FirstName"": ""FirstName"",
|
1249 |
1 |
""LastName"": ""LastName"",
|
1250 |
1 |
""lastName"": ""lastName"",
|
1251 |
1 |
}";
|
1252 |
||
1253 |
1 |
PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
|
1254 |
1 |
Assert.IsNotNull(o);
|
1255 |
||
1256 |
1 |
Assert.AreEqual("firstName", o.firstName);
|
1257 |
1 |
Assert.AreEqual("FirstName", o.FirstName);
|
1258 |
1 |
Assert.AreEqual("LastName", o.LastName);
|
1259 |
1 |
Assert.AreEqual("lastName", o.lastName);
|
1260 |
1 |
}
|
1261 |
||
1262 |
[Test] |
|
1263 |
public void DeserializePropertiesOnToNonDefaultConstructor() |
|
1264 |
{ |
|
1265 |
1 |
SubKlass i = new SubKlass("my subprop");
|
1266 |
1 |
i.SuperProp = "overrided superprop";
|
1267 |
||
1268 |
1 |
string json = JsonConvert.SerializeObject(i);
|
1269 |
1 |
Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
|
1270 |
||
1271 |
1 |
SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
|
1272 |
||
1273 |
1 |
string newJson = JsonConvert.SerializeObject(ii);
|
1274 |
1 |
Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
|
1275 |
1 |
}
|
1276 |
||
1277 |
[Test] |
|
1278 |
public void JsonPropertyWithHandlingValues() |
|
1279 |
{ |
|
1280 |
1 |
JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
|
1281 |
1 |
o.DefaultValueHandlingIgnoreProperty = "Default!";
|
1282 |
1 |
o.DefaultValueHandlingIncludeProperty = "Default!";
|
1283 |
||
1284 |
1 |
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
|
1285 |
||
1286 |
1 |
Assert.AreEqual(@"{
|
1287 |
1 |
""DefaultValueHandlingIncludeProperty"": ""Default!"",
|
1288 |
1 |
""NullValueHandlingIncludeProperty"": null,
|
1289 |
1 |
""ReferenceLoopHandlingErrorProperty"": null,
|
1290 |
1 |
""ReferenceLoopHandlingIgnoreProperty"": null,
|
1291 |
1 |
""ReferenceLoopHandlingSerializeProperty"": null
|
1292 |
1 |
}", json);
|
1293 |
||
1294 |
1 |
json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
|
1295 |
||
1296 |
1 |
Assert.AreEqual(@"{
|
1297 |
1 |
""DefaultValueHandlingIncludeProperty"": ""Default!"",
|
1298 |
1 |
""NullValueHandlingIncludeProperty"": null
|
1299 |
1 |
}", json);
|
1300 |
1 |
}
|
1301 |
||
1302 |
[Test] |
|
1303 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Self referencing loop")] |
|
1304 |
public void JsonPropertyWithHandlingValues_ReferenceLoopError() |
|
1305 |
{ |
|
1306 |
1 |
JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
|
1307 |
1 |
o.ReferenceLoopHandlingErrorProperty = o;
|
1308 |
||
1309 |
1 |
JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
|
1310 |
0 |
}
|
1311 |
||
1312 |
[Test] |
|
1313 |
public void PartialClassDeserialize() |
|
1314 |
{ |
|
1315 |
1 |
string json = @"{ |
1316 |
1 |
""request"": ""ux.settings.update"",
|
1317 |
1 |
""sid"": ""14c561bd-32a8-457e-b4e5-4bba0832897f"",
|
1318 |
1 |
""uid"": ""30c39065-0f31-de11-9442-001e3786a8ec"",
|
1319 |
1 |
""fidOrder"": [
|
1320 |
1 |
""id"",
|
1321 |
1 |
""andytest_name"",
|
1322 |
1 |
""andytest_age"",
|
1323 |
1 |
""andytest_address"",
|
1324 |
1 |
""andytest_phone"",
|
1325 |
1 |
""date"",
|
1326 |
1 |
""title"",
|
1327 |
1 |
""titleId""
|
1328 |
1 |
],
|
1329 |
1 |
""entityName"": ""Andy Test"",
|
1330 |
1 |
""setting"": ""entity.field.order""
|
1331 |
1 |
}";
|
1332 |
||
1333 |
1 |
RequestOnly r = JsonConvert.DeserializeObject<RequestOnly>(json);
|
1334 |
1 |
Assert.AreEqual("ux.settings.update", r.Request);
|
1335 |
||
1336 |
1 |
NonRequest n = JsonConvert.DeserializeObject<NonRequest>(json);
|
1337 |
1 |
Assert.AreEqual(new Guid("14c561bd-32a8-457e-b4e5-4bba0832897f"), n.Sid);
|
1338 |
1 |
Assert.AreEqual(new Guid("30c39065-0f31-de11-9442-001e3786a8ec"), n.Uid);
|
1339 |
1 |
Assert.AreEqual(8, n.FidOrder.Count);
|
1340 |
1 |
Assert.AreEqual("id", n.FidOrder[0]);
|
1341 |
1 |
Assert.AreEqual("titleId", n.FidOrder[n.FidOrder.Count - 1]);
|
1342 |
1 |
}
|
1343 |
||
1344 |
#if !SILVERLIGHT && !PocketPC && !NET20 |
|
1345 |
[MetadataType(typeof(OptInClassMetadata))] |
|
1346 |
public class OptInClass |
|
1347 |
{ |
|
1348 |
[DataContract] |
|
1349 |
public class OptInClassMetadata |
|
1350 |
{ |
|
1351 |
[DataMember] |
|
1352 |
public string Name { get; set; } |
|
1353 |
[DataMember] |
|
1354 |
public int Age { get; set; } |
|
1355 |
public string NotIncluded { get; set; } |
|
1356 |
} |
|
1357 |
||
1358 |
public string Name { get; set; } |
|
1359 |
public int Age { get; set; } |
|
1360 |
public string NotIncluded { get; set; } |
|
1361 |
} |
|
1362 |
||
1363 |
[Test] |
|
1364 |
public void OptInClassMetadataSerialization() |
|
1365 |
{ |
|
1366 |
1 |
OptInClass optInClass = new OptInClass();
|
1367 |
1 |
optInClass.Age = 26;
|
1368 |
1 |
optInClass.Name = "James NK";
|
1369 |
1 |
optInClass.NotIncluded = "Poor me :(";
|
1370 |
||
1371 |
1 |
string json = JsonConvert.SerializeObject(optInClass, Formatting.Indented);
|
1372 |
||
1373 |
1 |
Assert.AreEqual(@"{
|
1374 |
1 |
""Name"": ""James NK"",
|
1375 |
1 |
""Age"": 26
|
1376 |
1 |
}", json);
|
1377 |
||
1378 |
1 |
OptInClass newOptInClass = JsonConvert.DeserializeObject<OptInClass>(@"{ |
1379 |
1 |
""Name"": ""James NK"",
|
1380 |
1 |
""NotIncluded"": ""Ignore me!"",
|
1381 |
1 |
""Age"": 26
|
1382 |
1 |
}");
|
1383 |
1 |
Assert.AreEqual(26, newOptInClass.Age);
|
1384 |
1 |
Assert.AreEqual("James NK", newOptInClass.Name);
|
1385 |
1 |
Assert.AreEqual(null, newOptInClass.NotIncluded);
|
1386 |
1 |
}
|
1387 |
#endif |
|
1388 |
||
1389 |
#if !PocketPC && !NET20 |
|
1390 |
[DataContract] |
|
1391 |
public class DataContractPrivateMembers |
|
1392 |
{ |
|
1393 |
1 |
public DataContractPrivateMembers()
|
1394 |
{ |
|
1395 |
1 |
}
|
1396 |
||
1397 |
1 |
public DataContractPrivateMembers(string name, int age, int rank, string title)
|
1398 |
{ |
|
1399 |
1 |
_name = name;
|
1400 |
1 |
Age = age;
|
1401 |
1 |
Rank = rank;
|
1402 |
1 |
Title = title;
|
1403 |
1 |
}
|
1404 |
||
1405 |
[DataMember] |
|
1406 |
private string _name; |
|
1407 |
[DataMember(Name = "_age")] |
|
1408 |
private int Age { get; set; } |
|
1409 |
[JsonProperty] |
|
1410 |
private int Rank { get; set; } |
|
1411 |
[JsonProperty(PropertyName = "JsonTitle")] |
|
1412 |
[DataMember(Name = "DataTitle")] |
|
1413 |
private string Title { get; set; } |
|
1414 |
||
1415 |
public string NotIncluded { get; set; } |
|
1416 |
||
1417 |
public override string ToString() |
|
1418 |
{ |
|
1419 |
1 |
return "_name: " + _name + ", _age: " + Age + ", Rank: " + Rank + ", JsonTitle: " + Title;
|
1420 |
1 |
}
|
1421 |
} |
|
1422 |
||
1423 |
[Test] |
|
1424 |
public void SerializeDataContractPrivateMembers() |
|
1425 |
{ |
|
1426 |
1 |
DataContractPrivateMembers c = new DataContractPrivateMembers("Jeff", 26, 10, "Dr");
|
1427 |
1 |
c.NotIncluded = "Hi";
|
1428 |
1 |
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
|
1429 |
||
1430 |
1 |
Assert.AreEqual(@"{
|
1431 |
1 |
""_name"": ""Jeff"",
|
1432 |
1 |
""_age"": 26,
|
1433 |
1 |
""Rank"": 10,
|
1434 |
1 |
""JsonTitle"": ""Dr""
|
1435 |
1 |
}", json);
|
1436 |
||
1437 |
1 |
DataContractPrivateMembers cc = JsonConvert.DeserializeObject<DataContractPrivateMembers>(json);
|
1438 |
1 |
Assert.AreEqual("_name: Jeff, _age: 26, Rank: 10, JsonTitle: Dr", cc.ToString());
|
1439 |
1 |
}
|
1440 |
#endif |
|
1441 |
||
1442 |
[Test] |
|
1443 |
public void DeserializeDictionaryInterface() |
|
1444 |
{ |
|
1445 |
1 |
string json = @"{ |
1446 |
1 |
""Name"": ""Name!"",
|
1447 |
1 |
""Dictionary"": {
|
1448 |
1 |
""Item"": 11
|
1449 |
1 |
}
|
1450 |
1 |
}";
|
1451 |
||
1452 |
1 |
DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(json,
|
1453 |
1 |
new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace });
|
1454 |
1 |
Assert.AreEqual("Name!", c.Name);
|
1455 |
1 |
Assert.AreEqual(1, c.Dictionary.Count);
|
1456 |
1 |
Assert.AreEqual(11, c.Dictionary["Item"]);
|
1457 |
1 |
}
|
1458 |
||
1459 |
[Test] |
|
1460 |
public void DeserializeDictionaryInterfaceWithExistingValues() |
|
1461 |
{ |
|
1462 |
1 |
string json = @"{ |
1463 |
1 |
""Random"": {
|
1464 |
1 |
""blah"": 1
|
1465 |
1 |
},
|
1466 |
1 |
""Name"": ""Name!"",
|
1467 |
1 |
""Dictionary"": {
|
1468 |
1 |
""Item"": 11,
|
1469 |
1 |
""Item1"": 12
|
1470 |
1 |
},
|
1471 |
1 |
""Collection"": [
|
1472 |
1 |
999
|
1473 |
1 |
],
|
1474 |
1 |
""Employee"": {
|
1475 |
1 |
""Manager"": {
|
1476 |
1 |
""Name"": ""ManagerName!""
|
1477 |
1 |
}
|
1478 |
1 |
}
|
1479 |
1 |
}";
|
1480 |
||
1481 |
1 |
DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(json,
|
1482 |
1 |
new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Reuse });
|
1483 |
||
1484 |
1 |
Assert.AreEqual("Name!", c.Name);
|
1485 |
1 |
Assert.AreEqual(3, c.Dictionary.Count);
|
1486 |
1 |
Assert.AreEqual(11, c.Dictionary["Item"]);
|
1487 |
1 |
Assert.AreEqual(1, c.Dictionary["existing"]);
|
1488 |
1 |
Assert.AreEqual(4, c.Collection.Count);
|
1489 |
1 |
Assert.AreEqual(1, c.Collection.ElementAt(0));
|
1490 |
1 |
Assert.AreEqual(999, c.Collection.ElementAt(3));
|
1491 |
1 |
Assert.AreEqual("EmployeeName!", c.Employee.Name);
|
1492 |
1 |
Assert.AreEqual("ManagerName!", c.Employee.Manager.Name);
|
1493 |
1 |
Assert.IsNotNull(c.Random);
|
1494 |
1 |
}
|
1495 |
||
1496 |
[Test] |
|
1497 |
public void TypedObjectDeserializationWithComments() |
|
1498 |
{ |
|
1499 |
1 |
string json = @"/*comment*/ { /*comment*/
|
1500 |
1 |
""Name"": /*comment*/ ""Apple"" /*comment*/, /*comment*/
|
1501 |
1 |
""ExpiryDate"": ""\/Date(1230422400000)\/"",
|
1502 |
1 |
""Price"": 3.99,
|
1503 |
1 |
""Sizes"": /*comment*/ [ /*comment*/
|
1504 |
1 |
""Small"", /*comment*/
|
1505 |
1 |
""Medium"" /*comment*/,
|
1506 |
1 |
/*comment*/ ""Large""
|
1507 |
1 |
/*comment*/ ] /*comment*/
|
1508 |
1 |
} /*comment*/";
|
1509 |
||
1510 |
1 |
Product deserializedProduct = (Product)JsonConvert.DeserializeObject(json, typeof(Product));
|
1511 |
||
1512 |
1 |
Assert.AreEqual("Apple", deserializedProduct.Name);
|
1513 |
1 |
Assert.AreEqual(new DateTime(2008, 12, 28, 0, 0, 0, DateTimeKind.Utc), deserializedProduct.ExpiryDate);
|
1514 |
1 |
Assert.AreEqual(3.99, deserializedProduct.Price);
|
1515 |
1 |
Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
|
1516 |
1 |
Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
|
1517 |
1 |
Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
|
1518 |
1 |
}
|
1519 |
||
1520 |
[Test] |
|
1521 |
public void NestedInsideOuterObject() |
|
1522 |
{ |
|
1523 |
1 |
string json = @"{ |
1524 |
1 |
""short"": {
|
1525 |
1 |
""original"": ""http://www.contrast.ie/blog/online-marketing-2009/"",
|
1526 |
1 |
""short"": ""m2sqc6"",
|
1527 |
1 |
""shortened"": ""http://short.ie/m2sqc6"",
|
1528 |
1 |
""error"": {
|
1529 |
1 |
""code"": 0,
|
1530 |
1 |
""msg"": ""No action taken""
|
1531 |
1 |
}
|
1532 |
1 |
}
|
1533 |
1 |
}";
|
1534 |
||
1535 |
1 |
JObject o = JObject.Parse(json);
|
1536 |
||
1537 |
1 |
Shortie s = JsonConvert.DeserializeObject<Shortie>(o["short"].ToString());
|
1538 |
1 |
Assert.IsNotNull(s);
|
1539 |
||
1540 |
1 |
Assert.AreEqual(s.Original, "http://www.contrast.ie/blog/online-marketing-2009/");
|
1541 |
1 |
Assert.AreEqual(s.Short, "m2sqc6");
|
1542 |
1 |
Assert.AreEqual(s.Shortened, "http://short.ie/m2sqc6");
|
1543 |
1 |
}
|
1544 |
||
1545 |
[Test] |
|
1546 |
public void UriSerialization() |
|
1547 |
{ |
|
1548 |
1 |
Uri uri = new Uri("http://codeplex.com");
|
1549 |
1 |
string json = JsonConvert.SerializeObject(uri);
|
1550 |
||
1551 |
1 |
Assert.AreEqual("http://codeplex.com/", uri.ToString());
|
1552 |
||
1553 |
1 |
Uri newUri = JsonConvert.DeserializeObject<Uri>(json);
|
1554 |
1 |
Assert.AreEqual(uri, newUri);
|
1555 |
1 |
}
|
1556 |
||
1557 |
[Test] |
|
1558 |
public void AnonymousPlusLinqToSql() |
|
1559 |
{ |
|
1560 |
1 |
var value = new
|
1561 |
1 |
{
|
1562 |
1 |
bar = new JObject(new JProperty("baz", 13))
|
1563 |
1 |
};
|
1564 |
||
1565 |
1 |
string json = JsonConvert.SerializeObject(value);
|
1566 |
||
1567 |
1 |
Assert.AreEqual(@"{""bar"":{""baz"":13}}", json);
|
1568 |
1 |
}
|
1569 |
||
1570 |
[Test] |
|
1571 |
public void SerializeEnumerableAsObject() |
|
1572 |
{ |
|
1573 |
1 |
Content content = new Content
|
1574 |
1 |
{
|
1575 |
1 |
Text = "Blah, blah, blah",
|
1576 |
1 |
Children = new List<Content>
|
1577 |
1 |
{
|
1578 |
1 |
new Content { Text = "First" },
|
1579 |
1 |
new Content { Text = "Second" }
|
1580 |
1 |
}
|
1581 |
1 |
};
|
1582 |
||
1583 |
1 |
string json = JsonConvert.SerializeObject(content, Formatting.Indented);
|
1584 |
||
1585 |
1 |
Assert.AreEqual(@"{
|
1586 |
1 |
""Children"": [
|
1587 |
1 |
{
|
1588 |
1 |
""Children"": null,
|
1589 |
1 |
""Text"": ""First""
|
1590 |
1 |
},
|
1591 |
1 |
{
|
1592 |
1 |
""Children"": null,
|
1593 |
1 |
""Text"": ""Second""
|
1594 |
1 |
}
|
1595 |
1 |
],
|
1596 |
1 |
""Text"": ""Blah, blah, blah""
|
1597 |
1 |
}", json);
|
1598 |
1 |
}
|
1599 |
||
1600 |
[Test] |
|
1601 |
public void DeserializeEnumerableAsObject() |
|
1602 |
{ |
|
1603 |
1 |
string json = @"{ |
1604 |
1 |
""Children"": [
|
1605 |
1 |
{
|
1606 |
1 |
""Children"": null,
|
1607 |
1 |
""Text"": ""First""
|
1608 |
1 |
},
|
1609 |
1 |
{
|
1610 |
1 |
""Children"": null,
|
1611 |
1 |
""Text"": ""Second""
|
1612 |
1 |
}
|
1613 |
1 |
],
|
1614 |
1 |
""Text"": ""Blah, blah, blah""
|
1615 |
1 |
}";
|
1616 |
||
1617 |
1 |
Content content = JsonConvert.DeserializeObject<Content>(json);
|
1618 |
||
1619 |
1 |
Assert.AreEqual("Blah, blah, blah", content.Text);
|
1620 |
1 |
Assert.AreEqual(2, content.Children.Count);
|
1621 |
1 |
Assert.AreEqual("First", content.Children[0].Text);
|
1622 |
1 |
Assert.AreEqual("Second", content.Children[1].Text);
|
1623 |
1 |
}
|
1624 |
||
1625 |
[Test] |
|
1626 |
public void RoleTransferTest() |
|
1627 |
{ |
|
1628 |
1 |
string json = @"{""Operation"":""1"",""RoleName"":""Admin"",""Direction"":""0""}";
|
1629 |
||
1630 |
1 |
RoleTransfer r = JsonConvert.DeserializeObject<RoleTransfer>(json);
|
1631 |
||
1632 |
1 |
Assert.AreEqual(RoleTransferOperation.Second, r.Operation);
|
1633 |
1 |
Assert.AreEqual("Admin", r.RoleName);
|
1634 |
1 |
Assert.AreEqual(RoleTransferDirection.First, r.Direction);
|
1635 |
1 |
}
|
1636 |
||
1637 |
[Test] |
|
1638 |
public void PrimitiveValuesInObjectArray() |
|
1639 |
{ |
|
1640 |
1 |
string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",null],""type"":""rpc"",""tid"":2}";
|
1641 |
||
1642 |
1 |
ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
|
1643 |
||
1644 |
1 |
Assert.AreEqual("Router", o.Action);
|
1645 |
1 |
Assert.AreEqual("Navigate", o.Method);
|
1646 |
1 |
Assert.AreEqual(2, o.Data.Length);
|
1647 |
1 |
Assert.AreEqual("dashboard", o.Data[0]);
|
1648 |
1 |
Assert.AreEqual(null, o.Data[1]);
|
1649 |
1 |
}
|
1650 |
||
1651 |
[Test] |
|
1652 |
public void ComplexValuesInObjectArray() |
|
1653 |
{ |
|
1654 |
1 |
string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",[""id"", 1, ""teststring"", ""test""],{""one"":1}],""type"":""rpc"",""tid"":2}";
|
1655 |
||
1656 |
1 |
ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
|
1657 |
||
1658 |
1 |
Assert.AreEqual("Router", o.Action);
|
1659 |
1 |
Assert.AreEqual("Navigate", o.Method);
|
1660 |
1 |
Assert.AreEqual(3, o.Data.Length);
|
1661 |
1 |
Assert.AreEqual("dashboard", o.Data[0]);
|
1662 |
1 |
Assert.IsInstanceOfType(typeof(JArray), o.Data[1]);
|
1663 |
1 |
Assert.AreEqual(4, ((JArray)o.Data[1]).Count);
|
1664 |
1 |
Assert.IsInstanceOfType(typeof(JObject), o.Data[2]);
|
1665 |
1 |
Assert.AreEqual(1, ((JObject)o.Data[2]).Count);
|
1666 |
1 |
Assert.AreEqual(1, (int)((JObject)o.Data[2])["one"]);
|
1667 |
1 |
}
|
1668 |
||
1669 |
[Test] |
|
1670 |
public void DeserializeGenericDictionary() |
|
1671 |
{ |
|
1672 |
1 |
string json = @"{""key1"":""value1"",""key2"":""value2""}";
|
1673 |
||
1674 |
1 |
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
|
1675 |
||
1676 |
1 |
Console.WriteLine(values.Count);
|
1677 |
// 2 |
|
1678 |
||
1679 |
1 |
Console.WriteLine(values["key1"]);
|
1680 |
// value1 |
|
1681 |
||
1682 |
1 |
Assert.AreEqual(2, values.Count);
|
1683 |
1 |
Assert.AreEqual("value1", values["key1"]);
|
1684 |
1 |
Assert.AreEqual("value2", values["key2"]);
|
1685 |
1 |
}
|
1686 |
||
1687 |
[Test] |
|
1688 |
public void SerializeGenericList() |
|
1689 |
{ |
|
1690 |
1 |
Product p1 = new Product
|
1691 |
1 |
{
|
1692 |
1 |
Name = "Product 1",
|
1693 |
1 |
Price = 99.95m,
|
1694 |
1 |
ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
|
1695 |
1 |
};
|
1696 |
1 |
Product p2 = new Product
|
1697 |
1 |
{
|
1698 |
1 |
Name = "Product 2",
|
1699 |
1 |
Price = 12.50m,
|
1700 |
1 |
ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
|
1701 |
1 |
};
|
1702 |
||
1703 |
1 |
List<Product> products = new List<Product>();
|
1704 |
1 |
products.Add(p1);
|
1705 |
1 |
products.Add(p2);
|
1706 |
||
1707 |
1 |
string json = JsonConvert.SerializeObject(products, Formatting.Indented);
|
1708 |
//[ |
|
1709 |
// { |
|
1710 |
// "Name": "Product 1", |
|
1711 |
// "ExpiryDate": "\/Date(978048000000)\/", |
|
1712 |
// "Price": 99.95, |
|
1713 |
// "Sizes": null |
|
1714 |
// }, |
|
1715 |
// { |
|
1716 |
// "Name": "Product 2", |
|
1717 |
// "ExpiryDate": "\/Date(1248998400000)\/", |
|
1718 |
// "Price": 12.50, |
|
1719 |
// "Sizes": null |
|
1720 |
// } |
|
1721 |
//] |
|
1722 |
||
1723 |
1 |
Assert.AreEqual(@"[
|
1724 |
1 |
{
|
1725 |
1 |
""Name"": ""Product 1"",
|
1726 |
1 |
""ExpiryDate"": ""\/Date(978048000000)\/"",
|
1727 |
1 |
""Price"": 99.95,
|
1728 |
1 |
""Sizes"": null
|
1729 |
1 |
},
|
1730 |
1 |
{
|
1731 |
1 |
""Name"": ""Product 2"",
|
1732 |
1 |
""ExpiryDate"": ""\/Date(1248998400000)\/"",
|
1733 |
1 |
""Price"": 12.50,
|
1734 |
1 |
""Sizes"": null
|
1735 |
1 |
}
|
1736 |
1 |
]", json);
|
1737 |
1 |
}
|
1738 |
||
1739 |
[Test] |
|
1740 |
public void DeserializeGenericList() |
|
1741 |
{ |
|
1742 |
1 |
string json = @"[
|
1743 |
1 |
{
|
1744 |
1 |
""Name"": ""Product 1"",
|
1745 |
1 |
""ExpiryDate"": ""\/Date(978048000000)\/"",
|
1746 |
1 |
""Price"": 99.95,
|
1747 |
1 |
""Sizes"": null
|
1748 |
1 |
},
|
1749 |
1 |
{
|
1750 |
1 |
""Name"": ""Product 2"",
|
1751 |
1 |
""ExpiryDate"": ""\/Date(1248998400000)\/"",
|
1752 |
1 |
""Price"": 12.50,
|
1753 |
1 |
""Sizes"": null
|
1754 |
1 |
}
|
1755 |
1 |
]";
|
1756 |
||
1757 |
1 |
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
|
1758 |
||
1759 |
1 |
Console.WriteLine(products.Count);
|
1760 |
// 2 |
|
1761 |
||
1762 |
1 |
Product p1 = products[0];
|
1763 |
||
1764 |
1 |
Console.WriteLine(p1.Name);
|
1765 |
// Product 1 |
|
1766 |
||
1767 |
1 |
Assert.AreEqual(2, products.Count);
|
1768 |
1 |
Assert.AreEqual("Product 1", products[0].Name);
|
1769 |
1 |
}
|
1770 |
||
1771 |
#if !PocketPC && !NET20 |
|
1772 |
[Test] |
|
1773 |
public void DeserializeEmptyStringToNullableDateTime() |
|
1774 |
{ |
|
1775 |
1 |
string json = @"{""DateTimeField"":""""}";
|
1776 |
||
1777 |
1 |
NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json);
|
1778 |
1 |
Assert.AreEqual(null, c.DateTimeField);
|
1779 |
1 |
}
|
1780 |
#endif |
|
1781 |
||
1782 |
[Test] |
|
1783 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor or only one constructor with arguments.")] |
|
1784 |
public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments() |
|
1785 |
{ |
|
1786 |
1 |
string json = @"{""sublocation"":""AlertEmailSender.Program.Main"",""userId"":0,""type"":0,""summary"":""Loading settings variables"",""details"":null,""stackTrace"":"" at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n at System.Environment.get_StackTrace()\r\n at mr.Logging.Event..ctor(String summary) in C:\\Projects\\MRUtils\\Logging\\Event.vb:line 71\r\n at AlertEmailSender.Program.Main(String[] args) in C:\\Projects\\AlertEmailSender\\AlertEmailSender\\Program.cs:line 25"",""tag"":null,""time"":""\/Date(1249591032026-0400)\/""}";
|
1787 |
||
1788 |
1 |
Event e = JsonConvert.DeserializeObject<Event>(json);
|
1789 |
0 |
}
|
1790 |
||
1791 |
[Test] |
|
1792 |
public void DeserializeObjectSetOnlyProperty() |
|
1793 |
{ |
|
1794 |
1 |
string json = @"{'SetOnlyProperty':[1,2,3,4,5]}";
|
1795 |
||
1796 |
1 |
SetOnlyPropertyClass2 setOnly = JsonConvert.DeserializeObject<SetOnlyPropertyClass2>(json);
|
1797 |
1 |
JArray a = (JArray)setOnly.GetValue();
|
1798 |
1 |
Assert.AreEqual(5, a.Count);
|
1799 |
1 |
Assert.AreEqual(1, (int)a[0]);
|
1800 |
1 |
Assert.AreEqual(5, (int)a[a.Count - 1]);
|
1801 |
1 |
}
|
1802 |
||
1803 |
[Test] |
|
1804 |
public void DeserializeOptInClasses() |
|
1805 |
{ |
|
1806 |
1 |
string json = @"{id: ""12"", name: ""test"", items: [{id: ""112"", name: ""testing""}]}";
|
1807 |
||
1808 |
1 |
ListTestClass l = JsonConvert.DeserializeObject<ListTestClass>(json);
|
1809 |
1 |
}
|
1810 |
||
1811 |
[Test] |
|
1812 |
public void DeserializeNullableListWithNulls() |
|
1813 |
{ |
|
1814 |
1 |
List<decimal?> l = JsonConvert.DeserializeObject<List<decimal?>>("[ 3.3, null, 1.1 ] ");
|
1815 |
1 |
Assert.AreEqual(3, l.Count);
|
1816 |
||
1817 |
1 |
Assert.AreEqual(3.3m, l[0]);
|
1818 |
1 |
Assert.AreEqual(null, l[1]);
|
1819 |
1 |
Assert.AreEqual(1.1m, l[2]);
|
1820 |
1 |
}
|
1821 |
||
1822 |
[Test] |
|
1823 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON array into type 'Newtonsoft.Json.Tests.TestObjects.Person'.")] |
|
1824 |
public void CannotDeserializeArrayIntoObject() |
|
1825 |
{ |
|
1826 |
1 |
string json = @"[]";
|
1827 |
||
1828 |
1 |
JsonConvert.DeserializeObject<Person>(json);
|
1829 |
0 |
}
|
1830 |
||
1831 |
[Test] |
|
1832 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.")] |
|
1833 |
public void CannotDeserializeObjectIntoArray() |
|
1834 |
{ |
|
1835 |
1 |
string json = @"{}";
|
1836 |
||
1837 |
1 |
JsonConvert.DeserializeObject<List<Person>>(json);
|
1838 |
0 |
}
|
1839 |
||
1840 |
[Test] |
|
1841 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'.")] |
|
1842 |
public void CannotPopulateArrayIntoObject() |
|
1843 |
{ |
|
1844 |
1 |
string json = @"[]";
|
1845 |
||
1846 |
1 |
JsonConvert.PopulateObject(json, new Person());
|
1847 |
0 |
}
|
1848 |
||
1849 |
[Test] |
|
1850 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.")] |
|
1851 |
public void CannotPopulateObjectIntoArray() |
|
1852 |
{ |
|
1853 |
1 |
string json = @"{}";
|
1854 |
||
1855 |
1 |
JsonConvert.PopulateObject(json, new List<Person>());
|
1856 |
0 |
}
|
1857 |
||
1858 |
[Test] |
|
1859 |
public void DeserializeEmptyString() |
|
1860 |
{ |
|
1861 |
1 |
string json = @"{""Name"":""""}";
|
1862 |
||
1863 |
1 |
Person p = JsonConvert.DeserializeObject<Person>(json);
|
1864 |
1 |
Assert.AreEqual("", p.Name);
|
1865 |
1 |
}
|
1866 |
||
1867 |
[Test] |
|
1868 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.")] |
|
1869 |
public void SerializePropertyGetError() |
|
1870 |
{ |
|
1871 |
1 |
JsonConvert.SerializeObject(new MemoryStream());
|
1872 |
0 |
}
|
1873 |
||
1874 |
[Test] |
|
1875 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.")] |
|
1876 |
public void DeserializePropertySetError() |
|
1877 |
{ |
|
1878 |
1 |
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}");
|
1879 |
0 |
}
|
1880 |
||
1881 |
[Test] |
|
1882 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error converting value """" to type 'System.Int32'.")] |
|
1883 |
public void DeserializeEnsureTypeEmptyStringToIntError() |
|
1884 |
{ |
|
1885 |
1 |
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}");
|
1886 |
0 |
}
|
1887 |
||
1888 |
[Test] |
|
1889 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error converting value {null} to type 'System.Int32'.")] |
|
1890 |
public void DeserializeEnsureTypeNullToIntError() |
|
1891 |
{ |
|
1892 |
1 |
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}");
|
1893 |
0 |
}
|
1894 |
||
1895 |
[Test] |
|
1896 |
public void SerializeGenericListOfStrings() |
|
1897 |
{ |
|
1898 |
1 |
List<String> strings = new List<String>();
|
1899 |
||
1900 |
1 |
strings.Add("str_1");
|
1901 |
1 |
strings.Add("str_2");
|
1902 |
1 |
strings.Add("str_3");
|
1903 |
||
1904 |
1 |
string json = JsonConvert.SerializeObject(strings);
|
1905 |
1 |
Assert.AreEqual(@"[""str_1"",""str_2"",""str_3""]", json);
|
1906 |
1 |
}
|
1907 |
||
1908 |
[Test] |
|
1909 |
public void ConstructorReadonlyFieldsTest() |
|
1910 |
{ |
|
1911 |
1 |
ConstructorReadonlyFields c1 = new ConstructorReadonlyFields("String!", int.MaxValue);
|
1912 |
1 |
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
|
1913 |
1 |
Assert.AreEqual(@"{
|
1914 |
1 |
""A"": ""String!"",
|
1915 |
1 |
""B"": 2147483647
|
1916 |
1 |
}", json);
|
1917 |
||
1918 |
1 |
ConstructorReadonlyFields c2 = JsonConvert.DeserializeObject<ConstructorReadonlyFields>(json);
|
1919 |
1 |
Assert.AreEqual("String!", c2.A);
|
1920 |
1 |
Assert.AreEqual(int.MaxValue, c2.B);
|
1921 |
1 |
}
|
1922 |
||
1923 |
[Test] |
|
1924 |
public void SerializeStruct() |
|
1925 |
{ |
|
1926 |
1 |
StructTest structTest = new StructTest
|
1927 |
1 |
{
|
1928 |
1 |
StringProperty = "StringProperty!",
|
1929 |
1 |
StringField = "StringField",
|
1930 |
1 |
IntProperty = 5,
|
1931 |
1 |
IntField = 10
|
1932 |
1 |
};
|
1933 |
||
1934 |
1 |
string json = JsonConvert.SerializeObject(structTest, Formatting.Indented);
|
1935 |
1 |
Console.WriteLine(json);
|
1936 |
1 |
Assert.AreEqual(@"{
|
1937 |
1 |
""StringField"": ""StringField"",
|
1938 |
1 |
""IntField"": 10,
|
1939 |
1 |
""StringProperty"": ""StringProperty!"",
|
1940 |
1 |
""IntProperty"": 5
|
1941 |
1 |
}", json);
|
1942 |
||
1943 |
1 |
StructTest deserialized = JsonConvert.DeserializeObject<StructTest>(json);
|
1944 |
1 |
Assert.AreEqual(structTest.StringProperty, deserialized.StringProperty);
|
1945 |
1 |
Assert.AreEqual(structTest.StringField, deserialized.StringField);
|
1946 |
1 |
Assert.AreEqual(structTest.IntProperty, deserialized.IntProperty);
|
1947 |
1 |
Assert.AreEqual(structTest.IntField, deserialized.IntField);
|
1948 |
1 |
}
|
1949 |
||
1950 |
[Test] |
|
1951 |
public void SerializeListWithJsonConverter() |
|
1952 |
{ |
|
1953 |
1 |
Foo f = new Foo();
|
1954 |
1 |
f.Bars.Add(new Bar { Id = 0 });
|
1955 |
1 |
f.Bars.Add(new Bar { Id = 1 });
|
1956 |
1 |
f.Bars.Add(new Bar { Id = 2 });
|
1957 |
||
1958 |
1 |
string json = JsonConvert.SerializeObject(f, Formatting.Indented);
|
1959 |
1 |
Assert.AreEqual(@"{
|
1960 |
1 |
""Bars"": [
|
1961 |
1 |
0,
|
1962 |
1 |
1,
|
1963 |
1 |
2
|
1964 |
1 |
]
|
1965 |
1 |
}", json);
|
1966 |
||
1967 |
1 |
Foo newFoo = JsonConvert.DeserializeObject<Foo>(json);
|
1968 |
1 |
Assert.AreEqual(3, newFoo.Bars.Count);
|
1969 |
1 |
Assert.AreEqual(0, newFoo.Bars[0].Id);
|
1970 |
1 |
Assert.AreEqual(1, newFoo.Bars[1].Id);
|
1971 |
1 |
Assert.AreEqual(2, newFoo.Bars[2].Id);
|
1972 |
1 |
}
|
1973 |
||
1974 |
[Test] |
|
1975 |
public void SerializeGuidKeyedDictionary() |
|
1976 |
{ |
|
1977 |
1 |
Dictionary<Guid, int> dictionary = new Dictionary<Guid, int>();
|
1978 |
1 |
dictionary.Add(new Guid("F60EAEE0-AE47-488E-B330-59527B742D77"), 1);
|
1979 |
1 |
dictionary.Add(new Guid("C2594C02-EBA1-426A-AA87-8DD8871350B0"), 2);
|
1980 |
||
1981 |
1 |
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
|
1982 |
1 |
Assert.AreEqual(@"{
|
1983 |
1 |
""f60eaee0-ae47-488e-b330-59527b742d77"": 1,
|
1984 |
1 |
""c2594c02-eba1-426a-aa87-8dd8871350b0"": 2
|
1985 |
1 |
}", json);
|
1986 |
1 |
}
|
1987 |
||
1988 |
[Test] |
|
1989 |
public void SerializePersonKeyedDictionary() |
|
1990 |
{ |
|
1991 |
1 |
Dictionary<Person, int> dictionary = new Dictionary<Person, int>();
|
1992 |
1 |
dictionary.Add(new Person { Name = "p1" }, 1);
|
1993 |
1 |
dictionary.Add(new Person { Name = "p2" }, 2);
|
1994 |
||
1995 |
1 |
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
|
1996 |
||
1997 |
1 |
Assert.AreEqual(@"{
|
1998 |
1 |
""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
|
1999 |
1 |
""Newtonsoft.Json.Tests.TestObjects.Person"": 2
|
2000 |
1 |
}", json);
|
2001 |
1 |
}
|
2002 |
||
2003 |
[Test] |
|
2004 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object.")] |
|
2005 |
public void DeserializePersonKeyedDictionary() |
|
2006 |
{ |
|
2007 |
1 |
string json = |
2008 |
1 |
@"{
|
2009 |
1 |
""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
|
2010 |
1 |
""Newtonsoft.Json.Tests.TestObjects.Person"": 2
|
2011 |
1 |
}";
|
2012 |
||
2013 |
1 |
JsonConvert.DeserializeObject<Dictionary<Person, int>>(json);
|
2014 |
0 |
}
|
2015 |
||
2016 |
[Test] |
|
2017 |
public void SerializeFragment() |
|
2018 |
{ |
|
2019 |
1 |
string googleSearchText = @"{
|
2020 |
1 |
""responseData"": {
|
2021 |
1 |
""results"": [
|
2022 |
1 |
{
|
2023 |
1 |
""GsearchResultClass"": ""GwebSearch"",
|
2024 |
1 |
""unescapedUrl"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
|
2025 |
1 |
""url"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
|
2026 |
1 |
""visibleUrl"": ""en.wikipedia.org"",
|
2027 |
1 |
""cacheUrl"": ""http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org"",
|
2028 |
1 |
""title"": ""<b>Paris Hilton</b> - Wikipedia, the free encyclopedia"",
|
2029 |
1 |
""titleNoFormatting"": ""Paris Hilton - Wikipedia, the free encyclopedia"",
|
2030 |
1 |
""content"": ""[1] In 2006, she released her debut album...""
|
2031 |
1 |
},
|
2032 |
1 |
{
|
2033 |
1 |
""GsearchResultClass"": ""GwebSearch"",
|
2034 |
1 |
""unescapedUrl"": ""http://www.imdb.com/name/nm0385296/"",
|
2035 |
1 |
""url"": ""http://www.imdb.com/name/nm0385296/"",
|
2036 |
1 |
""visibleUrl"": ""www.imdb.com"",
|
2037 |
1 |
""cacheUrl"": ""http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com"",
|
2038 |
1 |
""title"": ""<b>Paris Hilton</b>"",
|
2039 |
1 |
""titleNoFormatting"": ""Paris Hilton"",
|
2040 |
1 |
""content"": ""Self: Zoolander. Socialite <b>Paris Hilton</b>...""
|
2041 |
1 |
}
|
2042 |
1 |
],
|
2043 |
1 |
""cursor"": {
|
2044 |
1 |
""pages"": [
|
2045 |
1 |
{
|
2046 |
1 |
""start"": ""0"",
|
2047 |
1 |
""label"": 1
|
2048 |
1 |
},
|
2049 |
1 |
{
|
2050 |
1 |
""start"": ""4"",
|
2051 |
1 |
""label"": 2
|
2052 |
1 |
},
|
2053 |
1 |
{
|
2054 |
1 |
""start"": ""8"",
|
2055 |
1 |
""label"": 3
|
2056 |
1 |
},
|
2057 |
1 |
{
|
2058 |
1 |
""start"": ""12"",
|
2059 |
1 |
""label"": 4
|
2060 |
1 |
}
|
2061 |
1 |
],
|
2062 |
1 |
""estimatedResultCount"": ""59600000"",
|
2063 |
1 |
""currentPageIndex"": 0,
|
2064 |
1 |
""moreResultsUrl"": ""http://www.google.com/search?oe=utf8&ie=utf8...""
|
2065 |
1 |
}
|
2066 |
1 |
},
|
2067 |
1 |
""responseDetails"": null,
|
2068 |
1 |
""responseStatus"": 200
|
2069 |
1 |
}";
|
2070 |
||
2071 |
1 |
JObject googleSearch = JObject.Parse(googleSearchText);
|
2072 |
||
2073 |
// get JSON result objects into a list |
|
2074 |
1 |
IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
|
2075 |
||
2076 |
// serialize JSON results into .NET objects |
|
2077 |
1 |
IList<SearchResult> searchResults = new List<SearchResult>();
|
2078 |
1 |
foreach (JToken result in results)
|
2079 |
{ |
|
2080 |
2 |
SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
|
2081 |
2 |
searchResults.Add(searchResult);
|
2082 |
} |
|
2083 |
||
2084 |
// Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia |
|
2085 |
// Content = [1] In 2006, she released her debut album... |
|
2086 |
// Url = http://en.wikipedia.org/wiki/Paris_Hilton |
|
2087 |
||
2088 |
// Title = <b>Paris Hilton</b> |
|
2089 |
// Content = Self: Zoolander. Socialite <b>Paris Hilton</b>... |
|
2090 |
// Url = http://www.imdb.com/name/nm0385296/ |
|
2091 |
||
2092 |
1 |
Assert.AreEqual(2, searchResults.Count);
|
2093 |
1 |
Assert.AreEqual("<b>Paris Hilton</b> - Wikipedia, the free encyclopedia", searchResults[0].Title);
|
2094 |
1 |
Assert.AreEqual("<b>Paris Hilton</b>", searchResults[1].Title);
|
2095 |
1 |
}
|
2096 |
||
2097 |
[Test] |
|
2098 |
public void DeserializeBaseReferenceWithDerivedValue() |
|
2099 |
{ |
|
2100 |
1 |
PersonPropertyClass personPropertyClass = new PersonPropertyClass();
|
2101 |
1 |
WagePerson wagePerson = (WagePerson)personPropertyClass.Person;
|
2102 |
||
2103 |
1 |
wagePerson.BirthDate = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
|
2104 |
1 |
wagePerson.Department = "McDees";
|
2105 |
1 |
wagePerson.HourlyWage = 12.50m;
|
2106 |
1 |
wagePerson.LastModified = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
|
2107 |
1 |
wagePerson.Name = "Jim Bob";
|
2108 |
||
2109 |
1 |
string json = JsonConvert.SerializeObject(personPropertyClass, Formatting.Indented);
|
2110 |
1 |
Assert.AreEqual(
|
2111 |
1 |
@"{
|
2112 |
1 |
""Person"": {
|
2113 |
1 |
""HourlyWage"": 12.50,
|
2114 |
1 |
""Name"": ""Jim Bob"",
|
2115 |
1 |
""BirthDate"": ""\/Date(975542399000)\/"",
|
2116 |
1 |
""LastModified"": ""\/Date(975542399000)\/""
|
2117 |
1 |
}
|
2118 |
1 |
}",
|
2119 |
1 |
json);
|
2120 |
||
2121 |
1 |
PersonPropertyClass newPersonPropertyClass = JsonConvert.DeserializeObject<PersonPropertyClass>(json);
|
2122 |
1 |
Assert.AreEqual(wagePerson.HourlyWage, ((WagePerson)newPersonPropertyClass.Person).HourlyWage);
|
2123 |
1 |
}
|
2124 |
||
2125 |
public class ExistingValueClass |
|
2126 |
{ |
|
2127 |
public Dictionary<string, string> Dictionary { get; set; } |
|
2128 |
public List<string> List { get; set; } |
|
2129 |
||
2130 |
1 |
public ExistingValueClass()
|
2131 |
{ |
|
2132 |
1 |
Dictionary = new Dictionary<string, string>
|
2133 |
1 |
{
|
2134 |
1 |
{"existing", "yup"}
|
2135 |
1 |
};
|
2136 |
1 |
List = new List<string>
|
2137 |
1 |
{
|
2138 |
1 |
"existing"
|
2139 |
1 |
};
|
2140 |
1 |
}
|
2141 |
} |
|
2142 |
||
2143 |
[Test] |
|
2144 |
public void DeserializePopulateDictionaryAndList() |
|
2145 |
{ |
|
2146 |
1 |
ExistingValueClass d = JsonConvert.DeserializeObject<ExistingValueClass>(@"{'Dictionary':{appended:'appended',existing:'new'}}");
|
2147 |
||
2148 |
1 |
Assert.IsNotNull(d);
|
2149 |
1 |
Assert.IsNotNull(d.Dictionary);
|
2150 |
1 |
Assert.AreEqual(typeof(Dictionary<string, string>), d.Dictionary.GetType());
|
2151 |
1 |
Assert.AreEqual(typeof(List<string>), d.List.GetType());
|
2152 |
1 |
Assert.AreEqual(2, d.Dictionary.Count);
|
2153 |
1 |
Assert.AreEqual("new", d.Dictionary["existing"]);
|
2154 |
1 |
Assert.AreEqual("appended", d.Dictionary["appended"]);
|
2155 |
1 |
Assert.AreEqual(1, d.List.Count);
|
2156 |
1 |
Assert.AreEqual("existing", d.List[0]);
|
2157 |
1 |
}
|
2158 |
||
2159 |
public interface IKeyValueId |
|
2160 |
{ |
|
2161 |
int Id { get; set; } |
|
2162 |
string Key { get; set; } |
|
2163 |
string Value { get; set; } |
|
2164 |
} |
|
2165 |
||
2166 |
||
2167 |
public class KeyValueId : IKeyValueId |
|
2168 |
{ |
|
2169 |
public int Id { get; set; } |
|
2170 |
public string Key { get; set; } |
|
2171 |
public string Value { get; set; } |
|
2172 |
} |
|
2173 |
||
2174 |
public class ThisGenericTest<T> where T : IKeyValueId |
|
2175 |
{ |
|
2176 |
2 |
private Dictionary<string, T> _dict1 = new Dictionary<string, T>();
|
2177 |
||
2178 |
public string MyProperty { get; set; } |
|
2179 |
||
2180 |
public void Add(T item) |
|
2181 |
{ |
|
2182 |
4 |
this._dict1.Add(item.Key, item);
|
2183 |
4 |
}
|
2184 |
||
2185 |
public T this[string key] |
|
2186 |
{ |
|
2187 |
0 |
get { return this._dict1[key]; }
|
2188 |
0 |
set { this._dict1[key] = value; }
|
2189 |
} |
|
2190 |
||
2191 |
public T this[int id] |
|
2192 |
{ |
|
2193 |
0 |
get { return this._dict1.Values.FirstOrDefault(x => x.Id == id); }
|
2194 |
set |
|
2195 |
{ |
|
2196 |
0 |
var item = this[id];
|
2197 |
||
2198 |
0 |
if (item == null)
|
2199 |
0 |
this.Add(value);
|
2200 |
else |
|
2201 |
0 |
this._dict1[item.Key] = value;
|
2202 |
0 |
}
|
2203 |
} |
|
2204 |
||
2205 |
public string ToJson() |
|
2206 |
{ |
|
2207 |
1 |
return JsonConvert.SerializeObject(this, Formatting.Indented);
|
2208 |
1 |
}
|
2209 |
||
2210 |
public T[] TheItems |
|
2211 |
{ |
|
2212 |
2 |
get { return this._dict1.Values.ToArray<T>(); }
|
2213 |
set |
|
2214 |
{ |
|
2215 |
1 |
foreach (var item in value)
|
2216 |
2 |
this.Add(item);
|
2217 |
1 |
}
|
2218 |
} |
|
2219 |
} |
|
2220 |
||
2221 |
[Test] |
|
2222 |
public void IgnoreIndexedProperties() |
|
2223 |
{ |
|
2224 |
1 |
ThisGenericTest<KeyValueId> g = new ThisGenericTest<KeyValueId>();
|
2225 |
||
2226 |
1 |
g.Add(new KeyValueId { Id = 1, Key = "key1", Value = "value1" });
|
2227 |
1 |
g.Add(new KeyValueId { Id = 2, Key = "key2", Value = "value2" });
|
2228 |
||
2229 |
1 |
g.MyProperty = "some value";
|
2230 |
||
2231 |
1 |
string json = g.ToJson();
|
2232 |
||
2233 |
1 |
Assert.AreEqual(@"{
|
2234 |
1 |
""MyProperty"": ""some value"",
|
2235 |
1 |
""TheItems"": [
|
2236 |
1 |
{
|
2237 |
1 |
""Id"": 1,
|
2238 |
1 |
""Key"": ""key1"",
|
2239 |
1 |
""Value"": ""value1""
|
2240 |
1 |
},
|
2241 |
1 |
{
|
2242 |
1 |
""Id"": 2,
|
2243 |
1 |
""Key"": ""key2"",
|
2244 |
1 |
""Value"": ""value2""
|
2245 |
1 |
}
|
2246 |
1 |
]
|
2247 |
1 |
}", json);
|
2248 |
||
2249 |
1 |
ThisGenericTest<KeyValueId> gen = JsonConvert.DeserializeObject<ThisGenericTest<KeyValueId>>(json);
|
2250 |
1 |
Assert.AreEqual("some value", gen.MyProperty);
|
2251 |
1 |
}
|
2252 |
||
2253 |
public class JRawValueTestObject |
|
2254 |
{ |
|
2255 |
public JRaw Value { get; set; } |
|
2256 |
} |
|
2257 |
||
2258 |
[Test] |
|
2259 |
public void JRawValue() |
|
2260 |
{ |
|
2261 |
1 |
JRawValueTestObject deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:3}");
|
2262 |
1 |
Assert.AreEqual("3", deserialized.Value.ToString());
|
2263 |
||
2264 |
1 |
deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:'3'}");
|
2265 |
1 |
Assert.AreEqual(@"""3""", deserialized.Value.ToString());
|
2266 |
1 |
}
|
2267 |
||
2268 |
[Test] |
|
2269 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor.")] |
|
2270 |
public void DeserializeDictionaryWithNoDefaultConstructor() |
|
2271 |
{ |
|
2272 |
1 |
string json = "{key1:'value',key2:'value',key3:'value'}";
|
2273 |
1 |
JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json);
|
2274 |
0 |
}
|
2275 |
||
2276 |
public class DictionaryWithNoDefaultConstructor : Dictionary<string, string> |
|
2277 |
{ |
|
2278 |
0 |
public DictionaryWithNoDefaultConstructor(IEnumerable<KeyValuePair<string, string>> initial)
|
2279 |
{ |
|
2280 |
0 |
foreach (KeyValuePair<string, string> pair in initial)
|
2281 |
{ |
|
2282 |
0 |
Add(pair.Key, pair.Value);
|
2283 |
} |
|
2284 |
0 |
}
|
2285 |
} |
|
2286 |
||
2287 |
[JsonObject(MemberSerialization.OptIn)] |
|
2288 |
public class A |
|
2289 |
{ |
|
2290 |
[JsonProperty("A1")] |
|
2291 |
private string _A1; |
|
2292 |
0 |
public string A1 { get { return _A1; } set { _A1 = value; } } |
2293 |
||
2294 |
[JsonProperty("A2")] |
|
2295 |
private string A2 { get; set; } |
|
2296 |
} |
|
2297 |
||
2298 |
[JsonObject(MemberSerialization.OptIn)] |
|
2299 |
public class B : A |
|
2300 |
{ |
|
2301 |
public string B1 { get; set; } |
|
2302 |
||
2303 |
[JsonProperty("B2")] |
|
2304 |
string _B2; |
|
2305 |
0 |
public string B2 { get { return _B2; } set { _B2 = value; } } |
2306 |
||
2307 |
[JsonProperty("B3")] |
|
2308 |
private string B3 { get; set; } |
|
2309 |
} |
|
2310 |
||
2311 |
[Test] |
|
2312 |
public void SerializeNonPublicBaseJsonProperties() |
|
2313 |
{ |
|
2314 |
1 |
B value = new B();
|
2315 |
1 |
string json = JsonConvert.SerializeObject(value, Formatting.Indented);
|
2316 |
||
2317 |
1 |
Assert.AreEqual(@"{
|
2318 |
1 |
""B2"": null,
|
2319 |
1 |
""A1"": null,
|
2320 |
1 |
""B3"": null,
|
2321 |
1 |
""A2"": null
|
2322 |
1 |
}", json);
|
2323 |
1 |
}
|
2324 |
||
2325 |
public class TestClass |
|
2326 |
{ |
|
2327 |
public string Key { get; set; } |
|
2328 |
public object Value { get; set; } |
|
2329 |
} |
|
2330 |
||
2331 |
[Test] |
|
2332 |
public void DeserializeToObjectProperty() |
|
2333 |
{ |
|
2334 |
1 |
var json = "{ Key: 'abc', Value: 123 }";
|
2335 |
1 |
var item = JsonConvert.DeserializeObject<TestClass>(json);
|
2336 |
||
2337 |
1 |
Assert.AreEqual(123, item.Value);
|
2338 |
1 |
}
|
2339 |
||
2340 |
public abstract class Animal |
|
2341 |
{ |
|
2342 |
public abstract string Name { get; } |
|
2343 |
} |
|
2344 |
||
2345 |
public class Human : Animal |
|
2346 |
{ |
|
2347 |
public override string Name |
|
2348 |
{ |
|
2349 |
1 |
get { return typeof(Human).Name; }
|
2350 |
} |
|
2351 |
||
2352 |
public string Ethnicity { get; set; } |
|
2353 |
} |
|
2354 |
||
2355 |
#if !NET20 && !PocketPC |
|
2356 |
public class DataContractJsonSerializerTestClass |
|
2357 |
{ |
|
2358 |
public TimeSpan TimeSpanProperty { get; set; } |
|
2359 |
public Guid GuidProperty { get; set; } |
|
2360 |
public Animal AnimalProperty { get; set; } |
|
2361 |
public Exception ExceptionProperty { get; set; } |
|
2362 |
} |
|
2363 |
||
2364 |
[Test] |
|
2365 |
public void DataContractJsonSerializerTest() |
|
2366 |
{ |
|
2367 |
1 |
Exception ex = new Exception("Blah blah blah");
|
2368 |
||
2369 |
1 |
DataContractJsonSerializerTestClass c = new DataContractJsonSerializerTestClass();
|
2370 |
1 |
c.TimeSpanProperty = new TimeSpan(200, 20, 59, 30, 900);
|
2371 |
1 |
c.GuidProperty = new Guid("66143115-BE2A-4a59-AF0A-348E1EA15B1E");
|
2372 |
1 |
c.AnimalProperty = new Human() { Ethnicity = "European" };
|
2373 |
1 |
c.ExceptionProperty = ex;
|
2374 |
||
2375 |
1 |
MemoryStream ms = new MemoryStream();
|
2376 |
1 |
DataContractJsonSerializer serializer = new DataContractJsonSerializer(
|
2377 |
1 |
typeof(DataContractJsonSerializerTestClass),
|
2378 |
1 |
new Type[] { typeof(Human) });
|
2379 |
1 |
serializer.WriteObject(ms, c);
|
2380 |
||
2381 |
1 |
byte[] jsonBytes = ms.ToArray();
|
2382 |
1 |
string json = Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
|
2383 |
||
2384 |
1 |
Console.WriteLine(JObject.Parse(json).ToString());
|
2385 |
1 |
Console.WriteLine();
|
2386 |
||
2387 |
1 |
Console.WriteLine(JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
|
2388 |
1 |
{
|
2389 |
1 |
// TypeNameHandling = TypeNameHandling.Objects
|
2390 |
1 |
}));
|
2391 |
1 |
}
|
2392 |
#endif |
|
2393 |
||
2394 |
public class ModelStateDictionary<T> : IDictionary<string, T> |
|
2395 |
{ |
|
2396 |
||
2397 |
0 |
private readonly Dictionary<string, T> _innerDictionary = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
|
2398 |
||
2399 |
2 |
public ModelStateDictionary()
|
2400 |
{ |
|
2401 |
2 |
}
|
2402 |
||
2403 |
0 |
public ModelStateDictionary(ModelStateDictionary<T> dictionary)
|
2404 |
{ |
|
2405 |
0 |
if (dictionary == null)
|
2406 |
{ |
|
2407 |
0 |
throw new ArgumentNullException("dictionary");
|
2408 |
} |
|
2409 |
||
2410 |
0 |
foreach (var entry in dictionary)
|
2411 |
{ |
|
2412 |
0 |
_innerDictionary.Add(entry.Key, entry.Value);
|
2413 |
} |
|
2414 |
0 |
}
|
2415 |
||
2416 |
public int Count |
|
2417 |
{ |
|
2418 |
get |
|
2419 |
{ |
|
2420 |
1 |
return _innerDictionary.Count;
|
2421 |
1 |
}
|
2422 |
} |
|
2423 |
||
2424 |
public bool IsReadOnly |
|
2425 |
{ |
|
2426 |
get |
|
2427 |
{ |
|
2428 |
0 |
return ((IDictionary<string, T>)_innerDictionary).IsReadOnly;
|
2429 |
0 |
}
|
2430 |
} |
|
2431 |
||
2432 |
public ICollection<string> Keys |
|
2433 |
{ |
|
2434 |
get |
|
2435 |
{ |
|
2436 |
0 |
return _innerDictionary.Keys;
|
2437 |
0 |
}
|
2438 |
} |
|
2439 |
||
2440 |
public T this[string key] |
|
2441 |
{ |
|
2442 |
get |
|
2443 |
{ |
|
2444 |
T value; |
|
2445 |
1 |
_innerDictionary.TryGetValue(key, out value);
|
2446 |
1 |
return value;
|
2447 |
1 |
}
|
2448 |
set |
|
2449 |
{ |
|
2450 |
1 |
_innerDictionary[key] = value;
|
2451 |
1 |
}
|
2452 |
} |
|
2453 |
||
2454 |
public ICollection<T> Values |
|
2455 |
{ |
|
2456 |
get |
|
2457 |
{ |
|
2458 |
0 |
return _innerDictionary.Values;
|
2459 |
0 |
}
|
2460 |
} |
|
2461 |
||
2462 |
public void Add(KeyValuePair<string, T> item) |
|
2463 |
{ |
|
2464 |
0 |
((IDictionary<string, T>)_innerDictionary).Add(item);
|
2465 |
0 |
}
|
2466 |
||
2467 |
public void Add(string key, T value) |
|
2468 |
{ |
|
2469 |
1 |
_innerDictionary.Add(key, value);
|
2470 |
1 |
}
|
2471 |
||
2472 |
public void Clear() |
|
2473 |
{ |
|
2474 |
0 |
_innerDictionary.Clear();
|
2475 |
0 |
}
|
2476 |
||
2477 |
public bool Contains(KeyValuePair<string, T> item) |
|
2478 |
{ |
|
2479 |
0 |
return ((IDictionary<string, T>)_innerDictionary).Contains(item);
|
2480 |
0 |
}
|
2481 |
||
2482 |
public bool ContainsKey(string key) |
|
2483 |
{ |
|
2484 |
0 |
return _innerDictionary.ContainsKey(key);
|
2485 |
0 |
}
|
2486 |
||
2487 |
public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex) |
|
2488 |
{ |
|
2489 |
0 |
((IDictionary<string, T>)_innerDictionary).CopyTo(array, arrayIndex);
|
2490 |
0 |
}
|
2491 |
||
2492 |
public IEnumerator<KeyValuePair<string, T>> GetEnumerator() |
|
2493 |
{ |
|
2494 |
1 |
return _innerDictionary.GetEnumerator();
|
2495 |
1 |
}
|
2496 |
||
2497 |
public void Merge(ModelStateDictionary<T> dictionary) |
|
2498 |
{ |
|
2499 |
0 |
if (dictionary == null)
|
2500 |
{ |
|
2501 |
0 |
return;
|
2502 |
} |
|
2503 |
||
2504 |
0 |
foreach (var entry in dictionary)
|
2505 |
{ |
|
2506 |
0 |
this[entry.Key] = entry.Value;
|
2507 |
} |
|
2508 |
0 |
}
|
2509 |
||
2510 |
public bool Remove(KeyValuePair<string, T> item) |
|
2511 |
{ |
|
2512 |
0 |
return ((IDictionary<string, T>)_innerDictionary).Remove(item);
|
2513 |
0 |
}
|
2514 |
||
2515 |
public bool Remove(string key) |
|
2516 |
{ |
|
2517 |
0 |
return _innerDictionary.Remove(key);
|
2518 |
0 |
}
|
2519 |
||
2520 |
public bool TryGetValue(string key, out T value) |
|
2521 |
{ |
|
2522 |
0 |
return _innerDictionary.TryGetValue(key, out value);
|
2523 |
0 |
}
|
2524 |
||
2525 |
IEnumerator IEnumerable.GetEnumerator() |
|
2526 |
{ |
|
2527 |
0 |
return ((IEnumerable)_innerDictionary).GetEnumerator();
|
2528 |
0 |
}
|
2529 |
} |
|
2530 |
||
2531 |
[Test] |
|
2532 |
public void SerializeNonIDictionary() |
|
2533 |
{ |
|
2534 |
1 |
ModelStateDictionary<string> modelStateDictionary = new ModelStateDictionary<string>();
|
2535 |
1 |
modelStateDictionary.Add("key", "value");
|
2536 |
||
2537 |
1 |
string json = JsonConvert.SerializeObject(modelStateDictionary);
|
2538 |
||
2539 |
1 |
Assert.AreEqual(@"{""key"":""value""}", json);
|
2540 |
||
2541 |
1 |
ModelStateDictionary<string> newModelStateDictionary = JsonConvert.DeserializeObject<ModelStateDictionary<string>>(json);
|
2542 |
1 |
Assert.AreEqual(1, newModelStateDictionary.Count);
|
2543 |
1 |
Assert.AreEqual("value", newModelStateDictionary["key"]);
|
2544 |
1 |
}
|
2545 |
||
2546 |
#if !SILVERLIGHT && !PocketPC |
|
2547 |
public class ISerializableTestObject : ISerializable |
|
2548 |
{ |
|
2549 |
internal string _stringValue; |
|
2550 |
internal int _intValue; |
|
2551 |
internal DateTimeOffset _dateTimeOffsetValue; |
|
2552 |
internal Person _personValue; |
|
2553 |
internal Person _nullPersonValue; |
|
2554 |
internal int? _nullableInt; |
|
2555 |
internal bool _booleanValue; |
|
2556 |
internal byte _byteValue; |
|
2557 |
internal char _charValue; |
|
2558 |
internal DateTime _dateTimeValue; |
|
2559 |
internal decimal _decimalValue; |
|
2560 |
internal short _shortValue; |
|
2561 |
internal long _longValue; |
|
2562 |
internal sbyte _sbyteValue; |
|
2563 |
internal float _floatValue; |
|
2564 |
internal ushort _ushortValue; |
|
2565 |
internal uint _uintValue; |
|
2566 |
internal ulong _ulongValue; |
|
2567 |
||
2568 |
1 |
public ISerializableTestObject(string stringValue, int intValue, DateTimeOffset dateTimeOffset, Person personValue)
|
2569 |
{ |
|
2570 |
1 |
_stringValue = stringValue;
|
2571 |
1 |
_intValue = intValue;
|
2572 |
1 |
_dateTimeOffsetValue = dateTimeOffset;
|
2573 |
1 |
_personValue = personValue;
|
2574 |
1 |
_dateTimeValue = new DateTime(0, DateTimeKind.Utc);
|
2575 |
1 |
}
|
2576 |
||
2577 |
1 |
protected ISerializableTestObject(SerializationInfo info, StreamingContext context)
|
2578 |
{ |
|
2579 |
1 |
_stringValue = info.GetString("stringValue");
|
2580 |
1 |
_intValue = info.GetInt32("intValue");
|
2581 |
1 |
_dateTimeOffsetValue = (DateTimeOffset)info.GetValue("dateTimeOffsetValue", typeof(DateTimeOffset));
|
2582 |
1 |
_personValue = (Person)info.GetValue("personValue", typeof(Person));
|
2583 |
1 |
_nullPersonValue = (Person)info.GetValue("nullPersonValue", typeof(Person));
|
2584 |
1 |
_nullableInt = (int?)info.GetValue("nullableInt", typeof(int?));
|
2585 |
||
2586 |
1 |
_booleanValue = info.GetBoolean("booleanValue");
|
2587 |
1 |
_byteValue = info.GetByte("byteValue");
|
2588 |
1 |
_charValue = info.GetChar("charValue");
|
2589 |
1 |
_dateTimeValue = info.GetDateTime("dateTimeValue");
|
2590 |
1 |
_decimalValue = info.GetDecimal("decimalValue");
|
2591 |
1 |
_shortValue = info.GetInt16("shortValue");
|
2592 |
1 |
_longValue = info.GetInt64("longValue");
|
2593 |
1 |
_sbyteValue = info.GetSByte("sbyteValue");
|
2594 |
1 |
_floatValue = info.GetSingle("floatValue");
|
2595 |
1 |
_ushortValue = info.GetUInt16("ushortValue");
|
2596 |
1 |
_uintValue = info.GetUInt32("uintValue");
|
2597 |
1 |
_ulongValue = info.GetUInt64("ulongValue");
|
2598 |
1 |
}
|
2599 |
||
2600 |
public void GetObjectData(SerializationInfo info, StreamingContext context) |
|
2601 |
{ |
|
2602 |
1 |
info.AddValue("stringValue", _stringValue);
|
2603 |
1 |
info.AddValue("intValue", _intValue);
|
2604 |
1 |
info.AddValue("dateTimeOffsetValue", _dateTimeOffsetValue);
|
2605 |
1 |
info.AddValue("personValue", _personValue);
|
2606 |
1 |
info.AddValue("nullPersonValue", _nullPersonValue);
|
2607 |
1 |
info.AddValue("nullableInt", null);
|
2608 |
||
2609 |
1 |
info.AddValue("booleanValue", _booleanValue);
|
2610 |
1 |
info.AddValue("byteValue", _byteValue);
|
2611 |
1 |
info.AddValue("charValue", _charValue);
|
2612 |
1 |
info.AddValue("dateTimeValue", _dateTimeValue);
|
2613 |
1 |
info.AddValue("decimalValue", _decimalValue);
|
2614 |
1 |
info.AddValue("shortValue", _shortValue);
|
2615 |
1 |
info.AddValue("longValue", _longValue);
|
2616 |
1 |
info.AddValue("sbyteValue", _sbyteValue);
|
2617 |
1 |
info.AddValue("floatValue", _floatValue);
|
2618 |
1 |
info.AddValue("ushortValue", _ushortValue);
|
2619 |
1 |
info.AddValue("uintValue", _uintValue);
|
2620 |
1 |
info.AddValue("ulongValue", _ulongValue);
|
2621 |
1 |
}
|
2622 |
} |
|
2623 |
||
2624 |
[Test] |
|
2625 |
public void SerializeISerializableTestObject() |
|
2626 |
{ |
|
2627 |
1 |
Person person = new Person();
|
2628 |
1 |
person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
|
2629 |
1 |
person.LastModified = person.BirthDate;
|
2630 |
1 |
person.Department = "Department!";
|
2631 |
1 |
person.Name = "Name!";
|
2632 |
||
2633 |
1 |
DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
|
2634 |
string dateTimeOffsetText; |
|
2635 |
#if !NET20 |
|
2636 |
1 |
dateTimeOffsetText = @"\/Date(977345999000+0200)\/";
|
2637 |
#else |
|
2638 |
dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00"; |
|
2639 |
#endif |
|
2640 |
||
2641 |
1 |
ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
|
2642 |
||
2643 |
1 |
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
|
2644 |
1 |
Assert.AreEqual(@"{
|
2645 |
1 |
""stringValue"": ""String!"",
|
2646 |
1 |
""intValue"": -2147483648,
|
2647 |
1 |
""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
|
2648 |
1 |
""personValue"": {
|
2649 |
1 |
""Name"": ""Name!"",
|
2650 |
1 |
""BirthDate"": ""\/Date(946688461000)\/"",
|
2651 |
1 |
""LastModified"": ""\/Date(946688461000)\/""
|
2652 |
1 |
},
|
2653 |
1 |
""nullPersonValue"": null,
|
2654 |
1 |
""nullableInt"": null,
|
2655 |
1 |
""booleanValue"": false,
|
2656 |
1 |
""byteValue"": 0,
|
2657 |
1 |
""charValue"": ""\u0000"",
|
2658 |
1 |
""dateTimeValue"": ""\/Date(-62135596800000)\/"",
|
2659 |
1 |
""decimalValue"": 0.0,
|
2660 |
1 |
""shortValue"": 0,
|
2661 |
1 |
""longValue"": 0,
|
2662 |
1 |
""sbyteValue"": 0,
|
2663 |
1 |
""floatValue"": 0.0,
|
2664 |
1 |
""ushortValue"": 0,
|
2665 |
1 |
""uintValue"": 0,
|
2666 |
1 |
""ulongValue"": 0
|
2667 |
1 |
}", json);
|
2668 |
||
2669 |
1 |
ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
|
2670 |
1 |
Assert.AreEqual("String!", o2._stringValue);
|
2671 |
1 |
Assert.AreEqual(int.MinValue, o2._intValue);
|
2672 |
1 |
Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
|
2673 |
1 |
Assert.AreEqual("Name!", o2._personValue.Name);
|
2674 |
1 |
Assert.AreEqual(null, o2._nullPersonValue);
|
2675 |
1 |
Assert.AreEqual(null, o2._nullableInt);
|
2676 |
1 |
}
|
2677 |
#endif |
|
2678 |
||
2679 |
public class KVPair<TKey, TValue> |
|
2680 |
{ |
|
2681 |
public TKey Key { get; set; } |
|
2682 |
public TValue Value { get; set; } |
|
2683 |
||
2684 |
2 |
public KVPair(TKey k, TValue v)
|
2685 |
{ |
|
2686 |
2 |
Key = k;
|
2687 |
2 |
Value = v;
|
2688 |
2 |
}
|
2689 |
} |
|
2690 |
||
2691 |
[Test] |
|
2692 |
public void DeserializeUsingNonDefaultConstructorWithLeftOverValues() |
|
2693 |
{ |
|
2694 |
1 |
List<KVPair<string, string>> kvPairs =
|
2695 |
1 |
JsonConvert.DeserializeObject<List<KVPair<string, string>>>(
|
2696 |
1 |
"[{\"Key\":\"Two\",\"Value\":\"2\"},{\"Key\":\"One\",\"Value\":\"1\"}]");
|
2697 |
||
2698 |
1 |
Assert.AreEqual(2, kvPairs.Count);
|
2699 |
1 |
Assert.AreEqual("Two", kvPairs[0].Key);
|
2700 |
1 |
Assert.AreEqual("2", kvPairs[0].Value);
|
2701 |
1 |
Assert.AreEqual("One", kvPairs[1].Key);
|
2702 |
1 |
Assert.AreEqual("1", kvPairs[1].Value);
|
2703 |
1 |
}
|
2704 |
||
2705 |
[Test] |
|
2706 |
public void SerializeClassWithInheritedProtectedMember() |
|
2707 |
{ |
|
2708 |
1 |
AA myA = new AA(2);
|
2709 |
1 |
string json = JsonConvert.SerializeObject(myA, Formatting.Indented);
|
2710 |
1 |
Assert.AreEqual(@"{
|
2711 |
1 |
""AA_field1"": 2,
|
2712 |
1 |
""AA_property1"": 2,
|
2713 |
1 |
""AA_property2"": 2,
|
2714 |
1 |
""AA_property3"": 2,
|
2715 |
1 |
""AA_property4"": 2
|
2716 |
1 |
}", json);
|
2717 |
||
2718 |
1 |
BB myB = new BB(3, 4);
|
2719 |
1 |
json = JsonConvert.SerializeObject(myB, Formatting.Indented);
|
2720 |
1 |
Assert.AreEqual(@"{
|
2721 |
1 |
""BB_field1"": 4,
|
2722 |
1 |
""BB_field2"": 4,
|
2723 |
1 |
""AA_field1"": 3,
|
2724 |
1 |
""BB_property1"": 4,
|
2725 |
1 |
""BB_property2"": 4,
|
2726 |
1 |
""BB_property3"": 4,
|
2727 |
1 |
""BB_property4"": 4,
|
2728 |
1 |
""BB_property5"": 4,
|
2729 |
1 |
""BB_property7"": 4,
|
2730 |
1 |
""AA_property1"": 3,
|
2731 |
1 |
""AA_property2"": 3,
|
2732 |
1 |
""AA_property3"": 3,
|
2733 |
1 |
""AA_property4"": 3
|
2734 |
1 |
}", json);
|
2735 |
1 |
}
|
2736 |
||
2737 |
[Test] |
|
2738 |
public void DeserializeClassWithInheritedProtectedMember() |
|
2739 |
{ |
|
2740 |
1 |
AA myA = JsonConvert.DeserializeObject<AA>( |
2741 |
1 |
@"{
|
2742 |
1 |
""AA_field1"": 2,
|
2743 |
1 |
""AA_field2"": 2,
|
2744 |
1 |
""AA_property1"": 2,
|
2745 |
1 |
""AA_property2"": 2,
|
2746 |
1 |
""AA_property3"": 2,
|
2747 |
1 |
""AA_property4"": 2,
|
2748 |
1 |
""AA_property5"": 2,
|
2749 |
1 |
""AA_property6"": 2
|
2750 |
1 |
}");
|
2751 |
||
2752 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
|
2753 |
1 |
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
|
2754 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
|
2755 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
|
2756 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myA));
|
2757 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myA));
|
2758 |
1 |
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myA));
|
2759 |
1 |
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myA));
|
2760 |
||
2761 |
1 |
BB myB = JsonConvert.DeserializeObject<BB>( |
2762 |
1 |
@"{
|
2763 |
1 |
""BB_field1"": 4,
|
2764 |
1 |
""BB_field2"": 4,
|
2765 |
1 |
""AA_field1"": 3,
|
2766 |
1 |
""AA_field2"": 3,
|
2767 |
1 |
""AA_property1"": 2,
|
2768 |
1 |
""AA_property2"": 2,
|
2769 |
1 |
""AA_property3"": 2,
|
2770 |
1 |
""AA_property4"": 2,
|
2771 |
1 |
""AA_property5"": 2,
|
2772 |
1 |
""AA_property6"": 2,
|
2773 |
1 |
""BB_property1"": 3,
|
2774 |
1 |
""BB_property2"": 3,
|
2775 |
1 |
""BB_property3"": 3,
|
2776 |
1 |
""BB_property4"": 3,
|
2777 |
1 |
""BB_property5"": 3,
|
2778 |
1 |
""BB_property6"": 3,
|
2779 |
1 |
""BB_property7"": 3,
|
2780 |
1 |
""BB_property8"": 3
|
2781 |
1 |
}");
|
2782 |
||
2783 |
1 |
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2784 |
1 |
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2785 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2786 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2787 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2788 |
1 |
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2789 |
1 |
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2790 |
1 |
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2791 |
||
2792 |
1 |
Assert.AreEqual(4, myB.BB_field1);
|
2793 |
1 |
Assert.AreEqual(4, myB.BB_field2);
|
2794 |
1 |
Assert.AreEqual(3, myB.BB_property1);
|
2795 |
1 |
Assert.AreEqual(3, myB.BB_property2);
|
2796 |
1 |
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property3", BindingFlags.Instance | BindingFlags.Public), myB));
|
2797 |
1 |
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
|
2798 |
1 |
Assert.AreEqual(0, myB.BB_property5);
|
2799 |
1 |
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property6", BindingFlags.Instance | BindingFlags.Public), myB));
|
2800 |
1 |
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property7", BindingFlags.Instance | BindingFlags.Public), myB));
|
2801 |
1 |
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property8", BindingFlags.Instance | BindingFlags.Public), myB));
|
2802 |
1 |
}
|
2803 |
||
2804 |
public class AA |
|
2805 |
{ |
|
2806 |
[JsonProperty] |
|
2807 |
protected int AA_field1; |
|
2808 |
protected int AA_field2; |
|
2809 |
[JsonProperty] |
|
2810 |
protected int AA_property1 { get; set; } |
|
2811 |
[JsonProperty] |
|
2812 |
protected int AA_property2 { get; private set; } |
|
2813 |
[JsonProperty] |
|
2814 |
protected int AA_property3 { private get; set; } |
|
2815 |
[JsonProperty] |
|
2816 |
private int AA_property4 { get; set; } |
|
2817 |
protected int AA_property5 { get; private set; } |
|
2818 |
protected int AA_property6 { private get; set; } |
|
2819 |
||
2820 |
2 |
public AA()
|
2821 |
{ |
|
2822 |
2 |
}
|
2823 |
||
2824 |
2 |
public AA(int f)
|
2825 |
{ |
|
2826 |
2 |
AA_field1 = f;
|
2827 |
2 |
AA_field2 = f;
|
2828 |
2 |
AA_property1 = f;
|
2829 |
2 |
AA_property2 = f;
|
2830 |
2 |
AA_property3 = f;
|
2831 |
2 |
AA_property4 = f;
|
2832 |
2 |
AA_property5 = f;
|
2833 |
2 |
AA_property6 = f;
|
2834 |
2 |
}
|
2835 |
} |
|
2836 |
||
2837 |
public class BB : AA |
|
2838 |
{ |
|
2839 |
[JsonProperty] |
|
2840 |
public int BB_field1; |
|
2841 |
public int BB_field2; |
|
2842 |
[JsonProperty] |
|
2843 |
public int BB_property1 { get; set; } |
|
2844 |
[JsonProperty] |
|
2845 |
public int BB_property2 { get; private set; } |
|
2846 |
[JsonProperty] |
|
2847 |
public int BB_property3 { private get; set; } |
|
2848 |
[JsonProperty] |
|
2849 |
private int BB_property4 { get; set; } |
|
2850 |
public int BB_property5 { get; private set; } |
|
2851 |
public int BB_property6 { private get; set; } |
|
2852 |
[JsonProperty] |
|
2853 |
public int BB_property7 { protected get; set; } |
|
2854 |
public int BB_property8 { protected get; set; } |
|
2855 |
||
2856 |
1 |
public BB()
|
2857 |
{ |
|
2858 |
1 |
}
|
2859 |
||
2860 |
1 |
public BB(int f, int g)
|
2861 |
1 |
: base(f)
|
2862 |
{ |
|
2863 |
1 |
BB_field1 = g;
|
2864 |
1 |
BB_field2 = g;
|
2865 |
1 |
BB_property1 = g;
|
2866 |
1 |
BB_property2 = g;
|
2867 |
1 |
BB_property3 = g;
|
2868 |
1 |
BB_property4 = g;
|
2869 |
1 |
BB_property5 = g;
|
2870 |
1 |
BB_property6 = g;
|
2871 |
1 |
BB_property7 = g;
|
2872 |
1 |
BB_property8 = g;
|
2873 |
1 |
}
|
2874 |
} |
|
2875 |
||
2876 |
#if !NET20 && !SILVERLIGHT |
|
2877 |
public class XNodeTestObject |
|
2878 |
{ |
|
2879 |
public XDocument Document { get; set; } |
|
2880 |
public XElement Element { get; set; } |
|
2881 |
} |
|
2882 |
#endif |
|
2883 |
||
2884 |
#if !SILVERLIGHT |
|
2885 |
public class XmlNodeTestObject |
|
2886 |
{ |
|
2887 |
public XmlDocument Document { get; set; } |
|
2888 |
} |
|
2889 |
#endif |
|
2890 |
||
2891 |
#if !NET20 && !SILVERLIGHT |
|
2892 |
[Test] |
|
2893 |
public void SerializeDeserializeXNodeProperties() |
|
2894 |
{ |
|
2895 |
1 |
XNodeTestObject testObject = new XNodeTestObject();
|
2896 |
1 |
testObject.Document = XDocument.Parse("<root>hehe, root</root>");
|
2897 |
1 |
testObject.Element = XElement.Parse(@"<fifth xmlns:json=""http://json.org"" json:Awesome=""true"">element</fifth>");
|
2898 |
||
2899 |
1 |
string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
|
2900 |
1 |
string expected = @"{ |
2901 |
1 |
""Document"": {
|
2902 |
1 |
""root"": ""hehe, root""
|
2903 |
1 |
},
|
2904 |
1 |
""Element"": {
|
2905 |
1 |
""fifth"": {
|
2906 |
1 |
""@xmlns:json"": ""http://json.org"",
|
2907 |
1 |
""@json:Awesome"": ""true"",
|
2908 |
1 |
""#text"": ""element""
|
2909 |
1 |
}
|
2910 |
1 |
}
|
2911 |
1 |
}";
|
2912 |
1 |
Assert.AreEqual(expected, json);
|
2913 |
||
2914 |
1 |
XNodeTestObject newTestObject = JsonConvert.DeserializeObject<XNodeTestObject>(json);
|
2915 |
1 |
Assert.AreEqual(testObject.Document.ToString(), newTestObject.Document.ToString());
|
2916 |
1 |
Assert.AreEqual(testObject.Element.ToString(), newTestObject.Element.ToString());
|
2917 |
||
2918 |
1 |
Assert.IsNull(newTestObject.Element.Parent);
|
2919 |
1 |
}
|
2920 |
#endif |
|
2921 |
||
2922 |
#if !SILVERLIGHT |
|
2923 |
[Test] |
|
2924 |
public void SerializeDeserializeXmlNodeProperties() |
|
2925 |
{ |
|
2926 |
1 |
XmlNodeTestObject testObject = new XmlNodeTestObject();
|
2927 |
1 |
XmlDocument document = new XmlDocument();
|
2928 |
1 |
document.LoadXml("<root>hehe, root</root>");
|
2929 |
1 |
testObject.Document = document;
|
2930 |
||
2931 |
1 |
string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
|
2932 |
1 |
string expected = @"{ |
2933 |
1 |
""Document"": {
|
2934 |
1 |
""root"": ""hehe, root""
|
2935 |
1 |
}
|
2936 |
1 |
}";
|
2937 |
1 |
Assert.AreEqual(expected, json);
|
2938 |
||
2939 |
1 |
XmlNodeTestObject newTestObject = JsonConvert.DeserializeObject<XmlNodeTestObject>(json);
|
2940 |
1 |
Assert.AreEqual(testObject.Document.InnerXml, newTestObject.Document.InnerXml);
|
2941 |
1 |
}
|
2942 |
#endif |
|
2943 |
||
2944 |
[Test] |
|
2945 |
public void FullClientMapSerialization() |
|
2946 |
{ |
|
2947 |
1 |
ClientMap source = new ClientMap()
|
2948 |
1 |
{
|
2949 |
1 |
position = new Pos() { X = 100, Y = 200 },
|
2950 |
1 |
center = new PosDouble() { X = 251.6, Y = 361.3 }
|
2951 |
1 |
};
|
2952 |
||
2953 |
1 |
string json = JsonConvert.SerializeObject(source, new PosConverter(), new PosDoubleConverter());
|
2954 |
1 |
Assert.AreEqual("{\"position\":new Pos(100,200),\"center\":new PosD(251.6,361.3)}", json);
|
2955 |
1 |
}
|
2956 |
||
2957 |
public class ClientMap |
|
2958 |
{ |
|
2959 |
public Pos position { get; set; } |
|
2960 |
public PosDouble center { get; set; } |
|
2961 |
} |
|
2962 |
||
2963 |
public class Pos |
|
2964 |
{ |
|
2965 |
public int X { get; set; } |
|
2966 |
public int Y { get; set; } |
|
2967 |
} |
|
2968 |
||
2969 |
public class PosDouble |
|
2970 |
{ |
|
2971 |
public double X { get; set; } |
|
2972 |
public double Y { get; set; } |
|
2973 |
} |
|
2974 |
||
2975 |
public class PosConverter : JsonConverter |
|
2976 |
{ |
|
2977 |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) |
|
2978 |
{ |
|
2979 |
1 |
Pos p = (Pos)value;
|
2980 |
||
2981 |
1 |
if (p != null)
|
2982 |
1 |
writer.WriteRawValue(String.Format("new Pos({0},{1})", p.X, p.Y));
|
2983 |
else |
|
2984 |
0 |
writer.WriteNull();
|
2985 |
1 |
}
|
2986 |
||
2987 |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) |
|
2988 |
{ |
|
2989 |
0 |
throw new NotImplementedException();
|
2990 |
} |
|
2991 |
||
2992 |
public override bool CanConvert(Type objectType) |
|
2993 |
{ |
|
2994 |
3 |
return objectType.IsAssignableFrom(typeof(Pos));
|
2995 |
3 |
}
|
2996 |
} |
|
2997 |
||
2998 |
public class PosDoubleConverter : JsonConverter |
|
2999 |
{ |
|
3000 |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) |
|
3001 |
{ |
|
3002 |
1 |
PosDouble p = (PosDouble)value;
|
3003 |
||
3004 |
1 |
if (p != null)
|
3005 |
1 |
writer.WriteRawValue(String.Format("new PosD({0},{1})", p.X, p.Y));
|
3006 |
else |
|
3007 |
0 |
writer.WriteNull();
|
3008 |
1 |
}
|
3009 |
||
3010 |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) |
|
3011 |
{ |
|
3012 |
0 |
throw new NotImplementedException();
|
3013 |
} |
|
3014 |
||
3015 |
public override bool CanConvert(Type objectType) |
|
3016 |
{ |
|
3017 |
2 |
return objectType.IsAssignableFrom(typeof(PosDouble));
|
3018 |
2 |
}
|
3019 |
} |
|
3020 |
||
3021 |
[Test] |
|
3022 |
public void TestEscapeDictionaryStrings() |
|
3023 |
{ |
|
3024 |
const string s = @"host\user"; |
|
3025 |
1 |
string serialized = JsonConvert.SerializeObject(s);
|
3026 |
1 |
Assert.AreEqual(@"""host\\user""", serialized);
|
3027 |
||
3028 |
1 |
Dictionary<int, object> d1 = new Dictionary<int, object>();
|
3029 |
1 |
d1.Add(5, s);
|
3030 |
1 |
Assert.AreEqual(@"{""5"":""host\\user""}", JsonConvert.SerializeObject(d1));
|
3031 |
||
3032 |
1 |
Dictionary<string, object> d2 = new Dictionary<string, object>();
|
3033 |
1 |
d2.Add(s, 5);
|
3034 |
1 |
Assert.AreEqual(@"{""host\\user"":5}", JsonConvert.SerializeObject(d2));
|
3035 |
1 |
}
|
3036 |
||
3037 |
public class GenericListTestClass |
|
3038 |
{ |
|
3039 |
public List<string> GenericList { get; set; } |
|
3040 |
||
3041 |
2 |
public GenericListTestClass()
|
3042 |
{ |
|
3043 |
2 |
GenericList = new List<string>();
|
3044 |
2 |
}
|
3045 |
} |
|
3046 |
||
3047 |
[Test] |
|
3048 |
public void DeserializeExistingGenericList() |
|
3049 |
{ |
|
3050 |
1 |
GenericListTestClass c = new GenericListTestClass();
|
3051 |
1 |
c.GenericList.Add("1");
|
3052 |
1 |
c.GenericList.Add("2");
|
3053 |
||
3054 |
1 |
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
|
3055 |
||
3056 |
1 |
GenericListTestClass newValue = JsonConvert.DeserializeObject<GenericListTestClass>(json);
|
3057 |
1 |
Assert.AreEqual(2, newValue.GenericList.Count);
|
3058 |
1 |
Assert.AreEqual(typeof(List<string>), newValue.GenericList.GetType());
|
3059 |
1 |
}
|
3060 |
||
3061 |
[Test] |
|
3062 |
public void DeserializeSimpleKeyValuePair() |
|
3063 |
{ |
|
3064 |
1 |
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
|
3065 |
1 |
list.Add(new KeyValuePair<string, string>("key1", "value1"));
|
3066 |
1 |
list.Add(new KeyValuePair<string, string>("key2", "value2"));
|
3067 |
||
3068 |
1 |
string json = JsonConvert.SerializeObject(list);
|
3069 |
||
3070 |
1 |
Assert.AreEqual(@"[{""Key"":""key1"",""Value"":""value1""},{""Key"":""key2"",""Value"":""value2""}]", json);
|
3071 |
||
3072 |
1 |
List<KeyValuePair<string, string>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(json);
|
3073 |
1 |
Assert.AreEqual(2, result.Count);
|
3074 |
1 |
Assert.AreEqual("key1", result[0].Key);
|
3075 |
1 |
Assert.AreEqual("value1", result[0].Value);
|
3076 |
1 |
Assert.AreEqual("key2", result[1].Key);
|
3077 |
1 |
Assert.AreEqual("value2", result[1].Value);
|
3078 |
1 |
}
|
3079 |
||
3080 |
[Test] |
|
3081 |
public void DeserializeComplexKeyValuePair() |
|
3082 |
{ |
|
3083 |
1 |
DateTime dateTime = new DateTime(2000, 12, 1, 23, 1, 1, DateTimeKind.Utc);
|
3084 |
||
3085 |
1 |
List<KeyValuePair<string, WagePerson>> list = new List<KeyValuePair<string, WagePerson>>();
|
3086 |
1 |
list.Add(new KeyValuePair<string, WagePerson>("key1", new WagePerson
|
3087 |
1 |
{
|
3088 |
1 |
BirthDate = dateTime,
|
3089 |
1 |
Department = "Department1",
|
3090 |
1 |
LastModified = dateTime,
|
3091 |
1 |
HourlyWage = 1
|
3092 |
1 |
}));
|
3093 |
1 |
list.Add(new KeyValuePair<string, WagePerson>("key2", new WagePerson
|
3094 |
1 |
{
|
3095 |
1 |
BirthDate = dateTime,
|
3096 |
1 |
Department = "Department2",
|
3097 |
1 |
LastModified = dateTime,
|
3098 |
1 |
HourlyWage = 2
|
3099 |
1 |
}));
|
3100 |
||
3101 |
1 |
string json = JsonConvert.SerializeObject(list, Formatting.Indented);
|
3102 |
||
3103 |
1 |
Assert.AreEqual(@"[
|
3104 |
1 |
{
|
3105 |
1 |
""Key"": ""key1"",
|
3106 |
1 |
""Value"": {
|
3107 |
1 |
""HourlyWage"": 1.0,
|
3108 |
1 |
""Name"": null,
|
3109 |
1 |
""BirthDate"": ""\/Date(975711661000)\/"",
|
3110 |
1 |
""LastModified"": ""\/Date(975711661000)\/""
|
3111 |
1 |
}
|
3112 |
1 |
},
|
3113 |
1 |
{
|
3114 |
1 |
""Key"": ""key2"",
|
3115 |
1 |
""Value"": {
|
3116 |
1 |
""HourlyWage"": 2.0,
|
3117 |
1 |
""Name"": null,
|
3118 |
1 |
""BirthDate"": ""\/Date(975711661000)\/"",
|
3119 |
1 |
""LastModified"": ""\/Date(975711661000)\/""
|
3120 |
1 |
}
|
3121 |
1 |
}
|
3122 |
1 |
]", json);
|
3123 |
||
3124 |
1 |
List<KeyValuePair<string, WagePerson>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, WagePerson>>>(json);
|
3125 |
1 |
Assert.AreEqual(2, result.Count);
|
3126 |
1 |
Assert.AreEqual("key1", result[0].Key);
|
3127 |
1 |
Assert.AreEqual(1, result[0].Value.HourlyWage);
|
3128 |
1 |
Assert.AreEqual("key2", result[1].Key);
|
3129 |
1 |
Assert.AreEqual(2, result[1].Value.HourlyWage);
|
3130 |
1 |
}
|
3131 |
||
3132 |
public class StringListAppenderConverter : JsonConverter |
|
3133 |
{ |
|
3134 |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) |
|
3135 |
{ |
|
3136 |
0 |
writer.WriteValue(value);
|
3137 |
0 |
}
|
3138 |
||
3139 |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) |
|
3140 |
{ |
|
3141 |
1 |
List<string> existingStrings = (List<string>)existingValue;
|
3142 |
1 |
List<string> newStrings = new List<string>(existingStrings);
|
3143 |
||
3144 |
1 |
reader.Read();
|
3145 |
||
3146 |
2 |
while (reader.TokenType != JsonToken.EndArray)
|
3147 |
{ |
|
3148 |
1 |
string s = (string)reader.Value;
|
3149 |
1 |
newStrings.Add(s);
|
3150 |
||
3151 |
1 |
reader.Read();
|
3152 |
} |
|
3153 |
||
3154 |
1 |
return newStrings;
|
3155 |
1 |
}
|
3156 |
||
3157 |
public override bool CanConvert(Type objectType) |
|
3158 |
{ |
|
3159 |
1 |
return (objectType == typeof (List<string>));
|
3160 |
1 |
}
|
3161 |
} |
|
3162 |
||
3163 |
[Test] |
|
3164 |
public void StringListAppenderConverterTest() |
|
3165 |
{ |
|
3166 |
1 |
Movie p = new Movie();
|
3167 |
1 |
p.ReleaseCountries = new List<string> { "Existing" };
|
3168 |
||
3169 |
1 |
JsonConvert.PopulateObject("{'ReleaseCountries':['Appended']}", p, new JsonSerializerSettings
|
3170 |
1 |
{
|
3171 |
1 |
Converters = new List<JsonConverter> { new StringListAppenderConverter() }
|
3172 |
1 |
});
|
3173 |
||
3174 |
1 |
Assert.AreEqual(2, p.ReleaseCountries.Count);
|
3175 |
1 |
Assert.AreEqual("Existing", p.ReleaseCountries[0]);
|
3176 |
1 |
Assert.AreEqual("Appended", p.ReleaseCountries[1]);
|
3177 |
1 |
}
|
3178 |
||
3179 |
public class StringAppenderConverter : JsonConverter |
|
3180 |
{ |
|
3181 |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) |
|
3182 |
{ |
|
3183 |
0 |
writer.WriteValue(value);
|
3184 |
0 |
}
|
3185 |
||
3186 |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) |
|
3187 |
{ |
|
3188 |
1 |
string existingString = (string)existingValue;
|
3189 |
1 |
string newString = existingString + (string)reader.Value;
|
3190 |
||
3191 |
1 |
return newString;
|
3192 |
1 |
}
|
3193 |
||
3194 |
public override bool CanConvert(Type objectType) |
|
3195 |
{ |
|
3196 |
1 |
return (objectType == typeof(string));
|
3197 |
1 |
}
|
3198 |
} |
|
3199 |
||
3200 |
[Test] |
|
3201 |
public void StringAppenderConverterTest() |
|
3202 |
{ |
|
3203 |
1 |
Movie p = new Movie();
|
3204 |
1 |
p.Name = "Existing,";
|
3205 |
||
3206 |
1 |
JsonConvert.PopulateObject("{'Name':'Appended'}", p, new JsonSerializerSettings
|
3207 |
1 |
{
|
3208 |
1 |
Converters = new List<JsonConverter> { new StringAppenderConverter() }
|
3209 |
1 |
});
|
3210 |
||
3211 |
1 |
Assert.AreEqual(p.Name, "Existing,Appended");
|
3212 |
1 |
}
|
3213 |
||
3214 |
[Test] |
|
3215 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property.")] |
|
3216 |
public void SerializeRefAdditionalContent() |
|
3217 |
{ |
|
3218 |
//Additional text found in JSON string after finishing deserializing object. |
|
3219 |
//Test 1 |
|
3220 |
1 |
var reference = new Dictionary<string, object>();
|
3221 |
1 |
reference.Add("$ref", "Persons");
|
3222 |
1 |
reference.Add("$id", 1);
|
3223 |
||
3224 |
1 |
var child = new Dictionary<string, object>();
|
3225 |
1 |
child.Add("_id", 2);
|
3226 |
1 |
child.Add("Name", "Isabell");
|
3227 |
1 |
child.Add("Father", reference);
|
3228 |
||
3229 |
1 |
var json = JsonConvert.SerializeObject(child);
|
3230 |
1 |
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
|
3231 |
0 |
}
|
3232 |
||
3233 |
[Test] |
|
3234 |
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JSON reference $ref property must have a string value.")] |
|
3235 |
public void SerializeRefBadType() |
|
3236 |
{ |
|
3237 |
//Additional text found in JSON string after finishing deserializing object. |
|
3238 |
//Test 1 |
|
3239 |
1 |
var reference = new Dictionary<string, object>();
|
3240 |
1 |
reference.Add("$ref", 1);
|
3241 |
1 |
reference.Add("$id", 1);
|
3242 |
||
3243 |
1 |
var child = new Dictionary<string, object>();
|
3244 |
1 |
child.Add("_id", 2);
|
3245 |
1 |
child.Add("Name", "Isabell");
|
3246 |
1 |
child.Add("Father", reference);
|
3247 |
||
3248 |
1 |
var json = JsonConvert.SerializeObject(child);
|
3249 |
1 |
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
|
3250 |
0 |
}
|
3251 |
||
3252 |
public class ConstructorCompexIgnoredProperty |
|
3253 |
{ |
|
3254 |
[JsonIgnore] |
|
3255 |
public Product Ignored { get; set; } |
|
3256 |
public string First { get; set; } |
|
3257 |
public int Second { get; set; } |
|
3258 |
||
3259 |
1 |
public ConstructorCompexIgnoredProperty(string first, int second)
|
3260 |
{ |
|
3261 |
1 |
First = first;
|
3262 |
1 |
Second = second;
|
3263 |
1 |
}
|
3264 |
} |
|
3265 |
||
3266 |
[Test] |
|
3267 |
public void DeserializeIgnoredPropertyInConstructor() |
|
3268 |
{ |
|
3269 |
1 |
string json = @"{""First"":""First"",""Second"":2,""Ignored"":{""Name"":""James""},""AdditionalContent"":{""LOL"":true}}";
|
3270 |
||
3271 |
1 |
ConstructorCompexIgnoredProperty cc = JsonConvert.DeserializeObject<ConstructorCompexIgnoredProperty>(json);
|
3272 |
1 |
Assert.AreEqual("First", cc.First);
|
3273 |
1 |
Assert.AreEqual(2, cc.Second);
|
3274 |
1 |
Assert.AreEqual(null, cc.Ignored);
|
3275 |
1 |
}
|
3276 |
||
3277 |
public class ShouldSerializeTestClass |
|
3278 |
{ |
|
3279 |
internal bool _shouldSerializeName; |
|
3280 |
||
3281 |
public string Name { get; set; } |
|
3282 |
public int Age { get; set; } |
|
3283 |
||
3284 |
public void ShouldSerializeAge() |
|
3285 |
{ |
|
3286 |
// dummy. should never be used because it doesn't return bool |
|
3287 |
0 |
}
|
3288 |
||
3289 |
public bool ShouldSerializeName() |
|
3290 |
{ |
|
3291 |
2 |
return _shouldSerializeName;
|
3292 |
2 |
}
|
3293 |
} |
|
3294 |
||
3295 |
[Test] |
|
3296 |
public void ShouldSerializeTest() |
|
3297 |
{ |
|
3298 |
1 |
ShouldSerializeTestClass c = new ShouldSerializeTestClass();
|
3299 |
1 |
c.Name = "James";
|
3300 |
1 |
c.Age = 27;
|
3301 |
||
3302 |
1 |
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
|
3303 |
||
3304 |
1 |
Assert.AreEqual(@"{
|
3305 |
1 |
""Age"": 27
|
3306 |
1 |
}", json);
|
3307 |
||
3308 |
1 |
c._shouldSerializeName = true;
|
3309 |
1 |
json = JsonConvert.SerializeObject(c, Formatting.Indented);
|
3310 |
||
3311 |
1 |
Assert.AreEqual(@"{
|
3312 |
1 |
""Name"": ""James"",
|
3313 |
1 |
""Age"": 27
|
3314 |
1 |
}", json);
|
3315 |
||
3316 |
1 |
ShouldSerializeTestClass deserialized = JsonConvert.DeserializeObject<ShouldSerializeTestClass>(json);
|
3317 |
1 |
Assert.AreEqual("James", deserialized.Name);
|
3318 |
1 |
Assert.AreEqual(27, deserialized.Age);
|
3319 |
1 |
}
|
3320 |
||
3321 |
public class Employee |
|
3322 |
{ |
|
3323 |
public string Name { get; set; } |
|
3324 |
public Employee Manager { get; set; } |
|
3325 |
||
3326 |
public bool ShouldSerializeManager() |
|
3327 |
{ |
|
3328 |
3 |
return (Manager != this);
|
3329 |
3 |
}
|
3330 |
} |
|
3331 |
||
3332 |
[Test] |
|
3333 |
public void ShouldSerializeExample() |
|
3334 |
{ |
|
3335 |
1 |
Employee joe = new Employee();
|
3336 |
1 |
joe.Name = "Joe Employee";
|
3337 |
1 |
Employee mike = new Employee();
|
3338 |
1 |
mike.Name = "Mike Manager";
|
3339 |
||
3340 |
1 |
joe.Manager = mike;
|
3341 |
1 |
mike.Manager = mike;
|
3342 |
||
3343 |
1 |
string json = JsonConvert.SerializeObject(new []{ joe, mike }, Formatting.Indented);
|
3344 |
// [ |
|
3345 |
// { |
|
3346 |
// "Name": "Joe Employee", |
|
3347 |
// "Manager": { |
|
3348 |
// "Name": "Mike Manager" |
|
3349 |
// } |
|
3350 |
// }, |
|
3351 |
// { |
|
3352 |
// "Name": "Mike Manager" |
|
3353 |
// } |
|
3354 |
// ] |
|
3355 |
||
3356 |
1 |
Console.WriteLine(json);
|
3357 |
1 |
}
|
3358 |
||
3359 |
public class DictionaryKey |
|
3360 |
{ |
|
3361 |
public string Value { get; set; } |
|
3362 |
||
3363 |
public override string ToString() |
|
3364 |
{ |
|
3365 |
2 |
return Value;
|
3366 |
2 |
}
|
3367 |
||
3368 |
public static implicit operator DictionaryKey(string value) |
|
3369 |
{ |
|
3370 |
3 |
return new DictionaryKey() {Value = value};
|
3371 |
3 |
}
|
3372 |
} |
|
3373 |
||
3374 |
[Test] |
|
3375 |
public void SerializeDeserializeDictionaryKey() |
|
3376 |
{ |
|
3377 |
1 |
Dictionary<DictionaryKey, string> dictionary = new Dictionary<DictionaryKey, string>();
|
3378 |
||
3379 |
1 |
dictionary.Add(new DictionaryKey() { Value = "First!" }, "First");
|
3380 |
1 |
dictionary.Add(new DictionaryKey() { Value = "Second!" }, "Second");
|
3381 |
||
3382 |
1 |
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
|
3383 |
||
3384 |
1 |
Assert.AreEqual(@"{
|
3385 |
1 |
""First!"": ""First"",
|
3386 |
1 |
""Second!"": ""Second""
|
3387 |
1 |
}", json);
|
3388 |
||
3389 |
1 |
Dictionary<DictionaryKey, string> newDictionary =
|
3390 |
1 |
JsonConvert.DeserializeObject<Dictionary<DictionaryKey, string>>(json);
|
3391 |
||
3392 |
1 |
Assert.AreEqual(2, newDictionary.Count);
|
3393 |
1 |
}
|
3394 |
||
3395 |
[Test] |
|
3396 |
public void SerializeNullableArray() |
|
3397 |
{ |
|
3398 |
1 |
string jsonText = JsonConvert.SerializeObject(new double?[] { 2.4, 4.3, null }, Formatting.Indented);
|
3399 |
||
3400 |
1 |
Assert.AreEqual(@"[
|
3401 |
1 |
2.4,
|
3402 |
1 |
4.3,
|
3403 |
1 |
null
|
3404 |
1 |
]", jsonText);
|
3405 |
||
3406 |
1 |
double?[] d = (double?[])JsonConvert.DeserializeObject(jsonText, typeof(double?[]));
|
3407 |
||
3408 |
1 |
Assert.AreEqual(3, d.Length);
|
3409 |
1 |
Assert.AreEqual(2.4, d[0]);
|
3410 |
1 |
Assert.AreEqual(4.3, d[1]);
|
3411 |
1 |
Assert.AreEqual(null, d[2]);
|
3412 |
1 |
}
|
3413 |
||
3414 |
#if !SILVERLIGHT && !NET20 && !PocketPC |
|
3415 |
[Test] |
|
3416 |
public void SerializeHashSet() |
|
3417 |
{ |
|
3418 |
1 |
string jsonText = JsonConvert.SerializeObject(new HashSet<string>()
|
3419 |
1 |
{
|
3420 |
1 |
"One",
|
3421 |
1 |
"2",
|
3422 |
1 |
"III"
|
3423 |
1 |
}, Formatting.Indented);
|
3424 |
||
3425 |
1 |
Assert.AreEqual(@"[
|
3426 |
1 |
""One"",
|
3427 |
1 |
""2"",
|
3428 |
1 |
""III""
|
3429 |
1 |
]", jsonText);
|
3430 |
||
3431 |
1 |
HashSet<string> d = JsonConvert.DeserializeObject<HashSet<string>>(jsonText);
|
3432 |
||
3433 |
1 |
Assert.AreEqual(3, d.Count);
|
3434 |
1 |
Assert.IsTrue(d.Contains("One"));
|
3435 |
1 |
Assert.IsTrue(d.Contains("2"));
|
3436 |
1 |
Assert.IsTrue(d.Contains("III"));
|
3437 |
1 |
}
|
3438 |
#endif |
|
3439 |
||
3440 |
private class MyClass |
|
3441 |
{ |
|
3442 |
public byte[] Prop1 { get; set; } |
|
3443 |
||
3444 |
2 |
public MyClass()
|
3445 |
{ |
|
3446 |
2 |
Prop1 = new byte[0];
|
3447 |
2 |
}
|
3448 |
} |
|
3449 |
||
3450 |
[Test] |
|
3451 |
public void DeserializeByteArray() |
|
3452 |
{ |
|
3453 |
1 |
JsonSerializer serializer1 = new JsonSerializer();
|
3454 |
1 |
serializer1.Converters.Add(new IsoDateTimeConverter());
|
3455 |
1 |
serializer1.NullValueHandling = NullValueHandling.Ignore;
|
3456 |
||
3457 |
1 |
string json = @"[{""Prop1"":""""},{""Prop1"":""""}]";
|
3458 |
||
3459 |
1 |
JsonTextReader reader = new JsonTextReader(new StringReader(json));
|
3460 |
||
3461 |
1 |
MyClass[] z = (MyClass[])serializer1.Deserialize(reader, typeof(MyClass[]));
|
3462 |
1 |
Assert.AreEqual(2, z.Length);
|
3463 |
1 |
Assert.AreEqual(0, z[0].Prop1.Length);
|
3464 |
1 |
Assert.AreEqual(0, z[1].Prop1.Length);
|
3465 |
1 |
}
|
3466 |
} |
|
3467 |
} |