~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to external/Newtonsoft.Json/Src/Newtonsoft.Json.Tests/Converters/JsonValueConverterTests.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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 Newtonsoft.Json.Converters;
 
28
#if !NETFX_CORE
 
29
using NUnit.Framework;
 
30
#else
 
31
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
 
32
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
 
33
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
 
34
using Windows.Data.Json;
 
35
using System.IO;
 
36
using System.Diagnostics;
 
37
using Newtonsoft.Json.Linq;
 
38
using System.Collections.Generic;
 
39
using System.Linq;
 
40
#endif
 
41
 
 
42
namespace Newtonsoft.Json.Tests.Converters
 
43
{
 
44
  [TestFixture]
 
45
  public class JsonValueConverterTests : TestFixtureBase
 
46
  {
 
47
    public class Computer
 
48
    {
 
49
      public string Cpu { get; set; }
 
50
      public List<string> Drives { get; set; }
 
51
    }
 
52
 
 
53
    [Test]
 
54
    public void WriteJson()
 
55
    {
 
56
      JsonObject o = JsonObject.Parse(@"{
 
57
  ""CPU"": ""Intel"",
 
58
  ""Drives"": [
 
59
    ""DVD read/writer"",
 
60
    ""500 gigabyte hard drive""
 
61
  ]
 
62
}");
 
63
 
 
64
      StringWriter sw = new StringWriter();
 
65
      JsonTextWriter writer = new JsonTextWriter(sw);
 
66
 
 
67
      JsonValueConverter converter = new JsonValueConverter();
 
68
      converter.WriteJson(writer, o, null);
 
69
 
 
70
      string json = sw.ToString();
 
71
 
 
72
      Assert.AreEqual(@"{""Drives"":[""DVD read/writer"",""500 gigabyte hard drive""],""CPU"":""Intel""}", json);
 
73
    }
 
74
 
 
75
    [Test]
 
76
    public void ReadJson()
 
77
    {
 
78
      string json = @"{
 
79
  ""CPU"": ""Intel"",
 
80
  ""Drives"": [
 
81
    ""DVD read/writer"",
 
82
    ""500 gigabyte hard drive""
 
83
  ]
 
84
}";
 
85
 
 
86
      JsonTextReader writer = new JsonTextReader(new StringReader(json));
 
87
 
 
88
      JsonValueConverter converter = new JsonValueConverter();
 
89
      JsonObject o = (JsonObject)converter.ReadJson(writer, typeof(JsonObject), null, null);
 
90
 
 
91
      Assert.AreEqual(2, o.Count);
 
92
      Assert.AreEqual("Intel", o.GetNamedString("CPU"));
 
93
      Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString());
 
94
      Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString());
 
95
    }
 
96
 
 
97
    [Test]
 
98
    public void ReadJsonComments()
 
99
    {
 
100
      string json = @"{/*comment!*/
 
101
  ""CPU"": ""Intel"",/*comment!*/
 
102
  ""Drives"": [/*comment!*/
 
103
    ""DVD read/writer"",
 
104
    /*comment!*/""500 gigabyte hard drive""
 
105
  ]/*comment!*/
 
106
}";
 
107
 
 
108
      JsonTextReader writer = new JsonTextReader(new StringReader(json));
 
109
 
 
110
      JsonValueConverter converter = new JsonValueConverter();
 
111
      JsonObject o = (JsonObject)converter.ReadJson(writer, typeof(JsonObject), null, null);
 
112
 
 
113
      Assert.AreEqual(2, o.Count);
 
114
      Assert.AreEqual("Intel", o.GetNamedString("CPU"));
 
115
      Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString());
 
116
      Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString());
 
117
    }
 
118
 
 
119
    [Test]
 
120
    public void ReadJsonNullValue()
 
121
    {
 
122
      string json = "null";
 
123
 
 
124
      JsonTextReader writer = new JsonTextReader(new StringReader(json));
 
125
 
 
126
      JsonValueConverter converter = new JsonValueConverter();
 
127
      JsonValue v = (JsonValue)converter.ReadJson(writer, typeof(JsonValue), null, null);
 
128
 
 
129
      Assert.AreEqual(JsonValueType.Null, v.ValueType);
 
130
    }
 
131
 
 
132
    [Test]
 
133
    public void ReadJsonUnsupportedValue()
 
134
    {
 
135
      string json = "undefined";
 
136
 
 
137
      JsonTextReader writer = new JsonTextReader(new StringReader(json));
 
138
 
 
139
      JsonValueConverter converter = new JsonValueConverter();
 
140
 
 
141
      ExceptionAssert.Throws<JsonException>("Unexpected or unsupported token: Undefined. Path '', line 1, position 9.",
 
142
      () =>
 
143
      {
 
144
        converter.ReadJson(writer, typeof(JsonValue), null, null);
 
145
      });
 
146
    }
 
147
 
 
148
    [Test]
 
149
    public void ReadJsonUnexpectedEndInArray()
 
150
    {
 
151
      string json = "[";
 
152
 
 
153
      JsonTextReader writer = new JsonTextReader(new StringReader(json));
 
154
 
 
155
      JsonValueConverter converter = new JsonValueConverter();
 
156
 
 
157
      ExceptionAssert.Throws<JsonException>("Unexpected end. Path '', line 1, position 1.",
 
158
      () =>
 
159
      {
 
160
        converter.ReadJson(writer, typeof(JsonValue), null, null);
 
161
      });
 
162
    }
 
163
 
 
164
    [Test]
 
165
    public void ReadJsonUnexpectedEndAfterComment()
 
166
    {
 
167
      string json = "[/*comment!*/";
 
168
 
 
169
      JsonTextReader writer = new JsonTextReader(new StringReader(json));
 
170
 
 
171
      JsonValueConverter converter = new JsonValueConverter();
 
172
 
 
173
      ExceptionAssert.Throws<JsonException>("Unexpected end. Path '', line 1, position 13.",
 
174
      () =>
 
175
      {
 
176
        converter.ReadJson(writer, typeof(JsonValue), null, null);
 
177
      });
 
178
    }
 
179
 
 
180
    [Test]
 
181
    public void ReadJsonUnexpectedEndInObject()
 
182
    {
 
183
      string json = "{'hi':";
 
184
 
 
185
      JsonTextReader writer = new JsonTextReader(new StringReader(json));
 
186
 
 
187
      JsonValueConverter converter = new JsonValueConverter();
 
188
 
 
189
      ExceptionAssert.Throws<JsonException>("Unexpected end. Path 'hi', line 1, position 6.",
 
190
      () =>
 
191
      {
 
192
        converter.ReadJson(writer, typeof(JsonValue), null, null);
 
193
      });
 
194
    }
 
195
 
 
196
    [Test]
 
197
    public void ReadJsonBadJsonType()
 
198
    {
 
199
      string json = "null";
 
200
 
 
201
      JsonTextReader writer = new JsonTextReader(new StringReader(json));
 
202
 
 
203
      JsonValueConverter converter = new JsonValueConverter();
 
204
 
 
205
      ExceptionAssert.Throws<JsonException>("Could not convert 'Windows.Data.Json.JsonValue' to 'Windows.Data.Json.JsonObject'. Path '', line 1, position 4.",
 
206
      () =>
 
207
      {
 
208
        converter.ReadJson(writer, typeof(JsonObject), null, null);
 
209
      });
 
210
    }
 
211
 
 
212
    [Test]
 
213
    public void JsonConvertDeserialize()
 
214
    {
 
215
      string json = @"[
 
216
  ""DVD read/writer"",
 
217
  ""500 gigabyte hard drive""
 
218
]";
 
219
 
 
220
      JsonArray a = JsonConvert.DeserializeObject<JsonArray>(json);
 
221
 
 
222
      Assert.AreEqual(2, a.Count);
 
223
      Assert.AreEqual("DVD read/writer", a[0].GetString());
 
224
      Assert.AreEqual("500 gigabyte hard drive", a[1].GetString());
 
225
    }
 
226
 
 
227
    [Test]
 
228
    public void JsonConvertSerialize()
 
229
    {
 
230
      JsonArray a = JsonArray.Parse(@"[
 
231
  ""DVD read/writer"",
 
232
  ""500 gigabyte hard drive""
 
233
]");
 
234
 
 
235
      string json = JsonConvert.SerializeObject(a, Formatting.Indented);
 
236
 
 
237
      Assert.AreEqual(@"[
 
238
  ""DVD read/writer"",
 
239
  ""500 gigabyte hard drive""
 
240
]", json);
 
241
    }
 
242
 
 
243
    [Test]
 
244
    public void SerializeDouble()
 
245
    {
 
246
      JsonObject o = new JsonObject();
 
247
      o["zero"] = JsonValue.CreateNumberValue(0);
 
248
      o["int"] = JsonValue.CreateNumberValue(1);
 
249
      o["smallfraction"] = JsonValue.CreateNumberValue(3.0000000000000009);
 
250
      o["double"] = JsonValue.CreateNumberValue(1.1);
 
251
      o["probablyint"] = JsonValue.CreateNumberValue(1.0);
 
252
      o["Epsilon"] = JsonValue.CreateNumberValue(double.Epsilon);
 
253
      o["MinValue"] = JsonValue.CreateNumberValue(double.MinValue);
 
254
      o["MaxValue"] = JsonValue.CreateNumberValue(double.MaxValue);
 
255
      o["NaN"] = JsonValue.CreateNumberValue(double.NaN);
 
256
      o["NegativeInfinity"] = JsonValue.CreateNumberValue(double.NegativeInfinity);
 
257
      o["PositiveInfinity"] = JsonValue.CreateNumberValue(double.PositiveInfinity);
 
258
 
 
259
      string json = JsonConvert.SerializeObject(o, Formatting.Indented);
 
260
 
 
261
      Assert.AreEqual(@"{
 
262
  ""PositiveInfinity"": Infinity,
 
263
  ""NegativeInfinity"": -Infinity,
 
264
  ""MinValue"": -1.7976931348623157E+308,
 
265
  ""double"": 1.1,
 
266
  ""int"": 1,
 
267
  ""zero"": 0,
 
268
  ""Epsilon"": 4.94065645841247E-324,
 
269
  ""MaxValue"": 1.7976931348623157E+308,
 
270
  ""NaN"": NaN,
 
271
  ""smallfraction"": 3.0000000000000009,
 
272
  ""probablyint"": 1
 
273
}", json);
 
274
    }
 
275
 
 
276
    [Test]
 
277
    public void DeserializePerformance()
 
278
    {
 
279
      string json = @"{
 
280
  ""CPU"": ""Intel"",
 
281
  ""Drives"": [
 
282
    ""DVD read/writer"",
 
283
    ""500 gigabyte hard drive""
 
284
  ]
 
285
}";
 
286
 
 
287
      Stopwatch timer = new Stopwatch();
 
288
      timer.Start();
 
289
      for (int i = 0; i < 100000; i++)
 
290
      {
 
291
        JsonObject o = JsonObject.Parse(json);
 
292
      }
 
293
      timer.Stop();
 
294
 
 
295
      string winrt = timer.Elapsed.TotalSeconds.ToString();
 
296
 
 
297
      timer = new Stopwatch();
 
298
      timer.Start();
 
299
      for (int i = 0; i < 100000; i++)
 
300
      {
 
301
        JObject o = JObject.Parse(json);
 
302
      }
 
303
      timer.Stop();
 
304
 
 
305
      string linq = timer.Elapsed.TotalSeconds.ToString();
 
306
 
 
307
      // warm up
 
308
      JsonConvert.DeserializeObject<Computer>(json);
 
309
 
 
310
      timer = new Stopwatch();
 
311
      timer.Start();
 
312
      for (int i = 0; i < 100000; i++)
 
313
      {
 
314
        Computer o = JsonConvert.DeserializeObject<Computer>(json);
 
315
      }
 
316
      timer.Stop();
 
317
 
 
318
      string jsonnet = timer.Elapsed.TotalSeconds.ToString();
 
319
 
 
320
      throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq));
 
321
      Console.WriteLine(winrt);
 
322
      Console.WriteLine(jsonnet);
 
323
    }
 
324
 
 
325
    [Test]
 
326
    public void SerializePerformance()
 
327
    {
 
328
      string json = @"{
 
329
  ""CPU"": ""Intel"",
 
330
  ""Drives"": [
 
331
    ""DVD read/writer"",
 
332
    ""500 gigabyte hard drive""
 
333
  ]
 
334
}";
 
335
 
 
336
      JsonObject o = JsonObject.Parse(json);
 
337
      JObject o1 = JObject.Parse(json);
 
338
      Computer o2 = JsonConvert.DeserializeObject<Computer>(json);
 
339
 
 
340
      Stopwatch timer = new Stopwatch();
 
341
      timer.Start();
 
342
      for (int i = 0; i < 100000; i++)
 
343
      {
 
344
        o.Stringify();
 
345
      }
 
346
      timer.Stop();
 
347
 
 
348
      string winrt = timer.Elapsed.TotalSeconds.ToString();
 
349
 
 
350
      timer.Start();
 
351
      for (int i = 0; i < 100000; i++)
 
352
      {
 
353
        o1.ToString(Formatting.None);
 
354
      }
 
355
      timer.Stop();
 
356
 
 
357
      string linq = timer.Elapsed.TotalSeconds.ToString();
 
358
 
 
359
      timer = new Stopwatch();
 
360
      timer.Start();
 
361
      for (int i = 0; i < 100000; i++)
 
362
      {
 
363
        JsonConvert.SerializeObject(o);
 
364
      }
 
365
      timer.Stop();
 
366
 
 
367
      string jsonnet = timer.Elapsed.TotalSeconds.ToString();
 
368
 
 
369
      throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq));
 
370
      Console.WriteLine(winrt);
 
371
      Console.WriteLine(jsonnet);
 
372
    }
 
373
 
 
374
    [Test]
 
375
    public void ParseJson()
 
376
    {
 
377
      string json = @"{
 
378
        ""channel"": {
 
379
          ""title"": ""James Newton-King"",
 
380
          ""link"": ""http://james.newtonking.com"",
 
381
          ""description"": ""James Newton-King's blog."",
 
382
          ""item"": [
 
383
            {
 
384
              ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
 
385
              ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
 
386
              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
 
387
              ""category"": [
 
388
                ""Json.NET"",
 
389
                ""CodePlex""
 
390
              ]
 
391
            }
 
392
          ]
 
393
        }
 
394
      }";
 
395
 
 
396
      // Windows.Data.Json
 
397
      // -----------------
 
398
      JsonObject jsonObject = JsonObject.Parse(json);
 
399
      string itemTitle1 = jsonObject["channel"].GetObject()["item"].GetArray()[0].GetObject()["title"].GetString();
 
400
      
 
401
      // LINQ to JSON
 
402
      // ------------
 
403
      JObject jObject = JObject.Parse(json);
 
404
      string itemTitle2 = (string)jObject["channel"]["item"][0]["title"];
 
405
    }
 
406
 
 
407
    [Test]
 
408
    public void CreateJson()
 
409
    {
 
410
      // Windows.Data.Json
 
411
      // -----------------
 
412
      JsonObject jsonObject = new JsonObject
 
413
        {
 
414
          {"CPU", JsonValue.CreateStringValue("Intel")},
 
415
          {"Drives", new JsonArray {
 
416
              JsonValue.CreateStringValue("DVD read/writer"),
 
417
              JsonValue.CreateStringValue("500 gigabyte hard drive")
 
418
            }
 
419
          }
 
420
        };
 
421
      string json1 = jsonObject.Stringify();
 
422
 
 
423
      // LINQ to JSON
 
424
      // ------------
 
425
      JObject jObject = new JObject
 
426
        {
 
427
          {"CPU", "Intel"},
 
428
          {"Drives", new JArray {
 
429
              "DVD read/writer",
 
430
              "500 gigabyte hard drive"
 
431
            }
 
432
          }
 
433
        };
 
434
      string json2 = jObject.ToString();
 
435
    }
 
436
 
 
437
    [Test]
 
438
    public void Converting()
 
439
    {
 
440
      JsonObject jsonObject = new JsonObject
 
441
        {
 
442
          {"CPU", JsonValue.CreateStringValue("Intel")},
 
443
          {"Drives", new JsonArray {
 
444
              JsonValue.CreateStringValue("DVD read/writer"),
 
445
              JsonValue.CreateStringValue("500 gigabyte hard drive")
 
446
            }
 
447
          }
 
448
        };
 
449
 
 
450
      // convert Windows.Data.Json to LINQ to JSON
 
451
      JObject o = JObject.FromObject(jsonObject);
 
452
 
 
453
      // convert LINQ to JSON to Windows.Data.Json
 
454
      JArray a = (JArray)o["Drives"];
 
455
      JsonArray jsonArray = a.ToObject<JsonArray>();
 
456
    }
 
457
  }
 
458
}
 
 
b'\\ No newline at end of file'