This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using Newtonsoft.Json;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class AspNetAjaxDateTimeConverterTest
|
||||
{
|
||||
public class DateTimeTestClass
|
||||
{
|
||||
public string PreField;
|
||||
public DateTime DateTimeField;
|
||||
public string PostField;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Serialize()
|
||||
{
|
||||
DateTimeTestClass c = new DateTimeTestClass();
|
||||
c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 12);
|
||||
c.PreField = "Pre";
|
||||
c.PostField = "Post";
|
||||
|
||||
string json = JavaScriptConvert.SerializeObject(c, new AspNetAjaxDateTimeConverter());
|
||||
|
||||
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""@1229083932012@"",""PostField"":""Post""}", json);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeSerialize()
|
||||
{
|
||||
DateTimeTestClass c =
|
||||
JavaScriptConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":""@1229083932012@"",""PostField"":""Post""}", new AspNetAjaxDateTimeConverter());
|
||||
|
||||
Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 12), c.DateTimeField);
|
||||
Assert.AreEqual("Pre", c.PreField);
|
||||
Assert.AreEqual("Post", c.PostField);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using Newtonsoft.Json;
|
||||
using System.IO;
|
||||
|
||||
namespace Newtonsoft.Json.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class JsonReaderTest
|
||||
{
|
||||
[Test]
|
||||
public void YahooFinance()
|
||||
{
|
||||
string input = @"{
|
||||
""matches"" : [
|
||||
{""t"":""C"", ""n"":""Citigroup Inc."", ""e"":""NYSE"", ""id"":""662713""}
|
||||
,{""t"":""CHL"", ""n"":""China Mobile Ltd. (ADR)"", ""e"":""NYSE"", ""id"":""660998""}
|
||||
,{""t"":""PTR"", ""n"":""PetroChina Company Limited (ADR)"", ""e"":""NYSE"", ""id"":""664536""}
|
||||
,{""t"":""RIO"", ""n"":""Companhia Vale do Rio Doce (ADR)"", ""e"":""NYSE"", ""id"":""671472""}
|
||||
,{""t"":""RIOPR"", ""n"":""Companhia Vale do Rio Doce (ADR)"", ""e"":""NYSE"", ""id"":""3512643""}
|
||||
,{""t"":""CSCO"", ""n"":""Cisco Systems, Inc."", ""e"":""NASDAQ"", ""id"":""99624""}
|
||||
,{""t"":""CVX"", ""n"":""Chevron Corporation"", ""e"":""NYSE"", ""id"":""667226""}
|
||||
,{""t"":""TM"", ""n"":""Toyota Motor Corporation (ADR)"", ""e"":""NYSE"", ""id"":""655880""}
|
||||
,{""t"":""JPM"", ""n"":""JPMorgan Chase \x26 Co."", ""e"":""NYSE"", ""id"":""665639""}
|
||||
,{""t"":""COP"", ""n"":""ConocoPhillips"", ""e"":""NYSE"", ""id"":""1691168""}
|
||||
,{""t"":""LFC"", ""n"":""China Life Insurance Company Ltd. (ADR)"", ""e"":""NYSE"", ""id"":""688679""}
|
||||
,{""t"":""NOK"", ""n"":""Nokia Corporation (ADR)"", ""e"":""NYSE"", ""id"":""657729""}
|
||||
,{""t"":""KO"", ""n"":""The Coca-Cola Company"", ""e"":""NYSE"", ""id"":""6550""}
|
||||
,{""t"":""VZ"", ""n"":""Verizon Communications Inc."", ""e"":""NYSE"", ""id"":""664887""}
|
||||
,{""t"":""AMX"", ""n"":""America Movil S.A.B de C.V. (ADR)"", ""e"":""NYSE"", ""id"":""665834""}],
|
||||
""all"" : false
|
||||
}
|
||||
";
|
||||
|
||||
using (JsonReader jsonReader = new JsonReader(new StringReader(input)))
|
||||
{
|
||||
while (jsonReader.Read())
|
||||
{
|
||||
Console.WriteLine(jsonReader.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadingIndented()
|
||||
{
|
||||
string input = @"{
|
||||
CPU: 'Intel',
|
||||
Drives: [
|
||||
'DVD read/writer',
|
||||
""500 gigabyte hard drive""
|
||||
]
|
||||
}";
|
||||
|
||||
StringReader sr = new StringReader(input);
|
||||
|
||||
using (JsonReader jsonReader = new JsonReader(sr))
|
||||
{
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.None);
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject);
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
|
||||
Assert.AreEqual(jsonReader.Value, "CPU");
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
|
||||
Assert.AreEqual(jsonReader.Value, "Intel");
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
|
||||
Assert.AreEqual(jsonReader.Value, "Drives");
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray);
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
|
||||
Assert.AreEqual(jsonReader.Value, "DVD read/writer");
|
||||
Assert.AreEqual(jsonReader.QuoteChar, '\'');
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
|
||||
Assert.AreEqual(jsonReader.Value, "500 gigabyte hard drive");
|
||||
Assert.AreEqual(jsonReader.QuoteChar, '"');
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray);
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadingEscapedStrings()
|
||||
{
|
||||
string input = "{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}";
|
||||
|
||||
StringReader sr = new StringReader(input);
|
||||
|
||||
using (JsonReader jsonReader = new JsonReader(sr))
|
||||
{
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject);
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
|
||||
Assert.AreEqual(jsonReader.Value, "Purple\r \n monkey's:\tdishwasher");
|
||||
Assert.AreEqual(jsonReader.QuoteChar, '\'');
|
||||
|
||||
jsonReader.Read();
|
||||
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadNewlineLastCharacter()
|
||||
{
|
||||
string input = @"{
|
||||
CPU: 'Intel',
|
||||
Drives: [
|
||||
'DVD read/writer',
|
||||
""500 gigabyte hard drive""
|
||||
]
|
||||
}" + '\n';
|
||||
|
||||
object o = JavaScriptConvert.DeserializeObject(input);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WriteReadWrite()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringWriter sw = new StringWriter(sb);
|
||||
|
||||
using (JsonWriter jsonWriter = new JsonWriter(sw))
|
||||
{
|
||||
jsonWriter.WriteStartArray();
|
||||
jsonWriter.WriteValue(true);
|
||||
|
||||
jsonWriter.WriteStartObject();
|
||||
jsonWriter.WritePropertyName("integer");
|
||||
jsonWriter.WriteValue(99);
|
||||
jsonWriter.WritePropertyName("string");
|
||||
jsonWriter.WriteValue("how now brown cow?");
|
||||
jsonWriter.WritePropertyName("array");
|
||||
|
||||
jsonWriter.WriteStartArray();
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
jsonWriter.WriteValue(i);
|
||||
}
|
||||
|
||||
jsonWriter.WriteStartObject();
|
||||
jsonWriter.WritePropertyName("decimal");
|
||||
jsonWriter.WriteValue(990.00990099m);
|
||||
jsonWriter.WriteEndObject();
|
||||
|
||||
jsonWriter.WriteValue(5);
|
||||
jsonWriter.WriteEndArray();
|
||||
|
||||
jsonWriter.WriteEndObject();
|
||||
|
||||
jsonWriter.WriteValue("This is a string.");
|
||||
jsonWriter.WriteNull();
|
||||
jsonWriter.WriteNull();
|
||||
jsonWriter.WriteEndArray();
|
||||
}
|
||||
|
||||
string json = sb.ToString();
|
||||
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
|
||||
object jsonObject = serializer.Deserialize(new JsonReader(new StringReader(json)));
|
||||
|
||||
sb = new StringBuilder();
|
||||
sw = new StringWriter(sb);
|
||||
|
||||
using (JsonWriter jsonWriter = new JsonWriter(sw))
|
||||
{
|
||||
serializer.Serialize(sw, jsonObject);
|
||||
}
|
||||
|
||||
Assert.AreEqual(json, sb.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using Newtonsoft.Json;
|
||||
using System.IO;
|
||||
using System.Collections;
|
||||
using System.Xml;
|
||||
using System.Xml.Serialization;
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace Newtonsoft.Json.Tests
|
||||
{
|
||||
public class Product
|
||||
{
|
||||
public string Name;
|
||||
public DateTime Expiry;
|
||||
public decimal Price;
|
||||
public string[] Sizes;
|
||||
}
|
||||
|
||||
public class Store
|
||||
{
|
||||
public StoreColor Color = StoreColor.Yellow;
|
||||
public DateTime Establised = new DateTime(2010, 1, 22);
|
||||
public double Width = 1.1;
|
||||
public int Employees = 999;
|
||||
public int[] RoomsPerFloor = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||
public bool Open = false;
|
||||
public char Symbol = '@';
|
||||
public List<string> Mottos = new List<string>();
|
||||
public decimal Cost = 100980.1M;
|
||||
public string Escape = "\r\n\t\f\b?{\\r\\n\"\'";
|
||||
public List<Product> product = new List<Product>();
|
||||
|
||||
public Store()
|
||||
{
|
||||
Mottos.Add("Hello World");
|
||||
Mottos.Add("öäüÖÄÜ\\'{new Date(12345);}[222]_µ@²³~");
|
||||
Mottos.Add(null);
|
||||
Mottos.Add(" ");
|
||||
|
||||
Product rocket = new Product();
|
||||
rocket.Name = "Rocket";
|
||||
rocket.Expiry = new DateTime(2000, 2, 2, 23, 1, 30);
|
||||
Product alien = new Product();
|
||||
alien.Name = "Alien";
|
||||
|
||||
product.Add(rocket);
|
||||
product.Add(alien);
|
||||
}
|
||||
}
|
||||
|
||||
public enum StoreColor
|
||||
{
|
||||
Black,
|
||||
Red,
|
||||
Yellow,
|
||||
White
|
||||
}
|
||||
|
||||
[TestFixture]
|
||||
public class JsonSerializerTest
|
||||
{
|
||||
[Test]
|
||||
public void PersonTypedObjectDeserialization()
|
||||
{
|
||||
Store store = new Store();
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeObject(store);
|
||||
|
||||
Store deserializedStore = (Store)JavaScriptConvert.DeserializeObject(jsonText, typeof(Store));
|
||||
|
||||
Console.WriteLine(jsonText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TypedObjectDeserialization()
|
||||
{
|
||||
Product product = new Product();
|
||||
|
||||
product.Name = "Apple";
|
||||
product.Expiry = new DateTime(2008, 12, 28);
|
||||
product.Price = 3.99M;
|
||||
product.Sizes = new string[] { "Small", "Medium", "Large" };
|
||||
|
||||
string output = JavaScriptConvert.SerializeObject(product);
|
||||
//{
|
||||
// "Name": "Apple",
|
||||
// "Expiry": new Date(1230422400000),
|
||||
// "Price": 3.99,
|
||||
// "Sizes": [
|
||||
// "Small",
|
||||
// "Medium",
|
||||
// "Large"
|
||||
// ]
|
||||
//}
|
||||
|
||||
Product deserializedProduct = (Product)JavaScriptConvert.DeserializeObject(output, typeof(Product));
|
||||
|
||||
Assert.AreEqual("Apple", deserializedProduct.Name);
|
||||
Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.Expiry);
|
||||
Assert.AreEqual(3.99, deserializedProduct.Price);
|
||||
Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
|
||||
Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
|
||||
Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JavaScriptConvertSerializer()
|
||||
{
|
||||
string value = @"{""Name"":""Orange"", ""Price"":3.99, ""Expiry"":""01/24/2010 12:00:00""}";
|
||||
|
||||
Product p = JavaScriptConvert.DeserializeObject(value, typeof(Product)) as Product;
|
||||
|
||||
Assert.AreEqual("Orange", p.Name);
|
||||
Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.Expiry);
|
||||
Assert.AreEqual(3.99, p.Price);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeJavaScriptDate()
|
||||
{
|
||||
DateTime dateValue = new DateTime(2000, 3, 30);
|
||||
Dictionary<string, object> testDictionary = new Dictionary<string, object>();
|
||||
testDictionary["date"] = dateValue;
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeObject(testDictionary);
|
||||
|
||||
Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JavaScriptConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
|
||||
DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
|
||||
|
||||
Assert.AreEqual(dateValue, deserializedDate);
|
||||
|
||||
Console.WriteLine("DeserializeJavaScriptDate");
|
||||
Console.WriteLine(jsonText);
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(jsonText);
|
||||
}
|
||||
|
||||
public class MethodExecutorObject
|
||||
{
|
||||
public string serverClassName;
|
||||
public object[] serverMethodParams;
|
||||
public string clientGetResultFunction;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestMethodExecutorObject()
|
||||
{
|
||||
MethodExecutorObject executorObject = new MethodExecutorObject();
|
||||
executorObject.serverClassName = "BanSubs";
|
||||
executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
|
||||
executorObject.clientGetResultFunction = "ClientBanSubsCB";
|
||||
|
||||
string output = JavaScriptConvert.SerializeObject(executorObject);
|
||||
|
||||
MethodExecutorObject executorObject2 = JavaScriptConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
|
||||
|
||||
Assert.AreNotSame(executorObject, executorObject2);
|
||||
Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
|
||||
Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
|
||||
Assert.Contains("101", executorObject2.serverMethodParams);
|
||||
Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HashtableDeserialization()
|
||||
{
|
||||
string value = @"{""Name"":""Orange"", ""Price"":3.99, ""Expiry"":""01/24/2010 12:00:00""}";
|
||||
|
||||
Hashtable p = JavaScriptConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
|
||||
|
||||
Assert.AreEqual("Orange", p["Name"].ToString());
|
||||
}
|
||||
|
||||
public class TypedSubHashtable
|
||||
{
|
||||
public string Name;
|
||||
public Hashtable Hash;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TypedHashtableDeserialization()
|
||||
{
|
||||
string value = @"{""Name"":""Orange"", ""Hash"":{""Expiry"":""01/24/2010 12:00:00""}}";
|
||||
|
||||
TypedSubHashtable p = JavaScriptConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
|
||||
|
||||
Assert.AreEqual("01/24/2010 12:00:00", p.Hash["Expiry"].ToString());
|
||||
}
|
||||
|
||||
public class GetOnlyPropertyClass
|
||||
{
|
||||
public string Field = "Field";
|
||||
|
||||
public string GetOnlyProperty
|
||||
{
|
||||
get { return "GetOnlyProperty"; }
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SerializeDeserializeGetOnlyProperty()
|
||||
{
|
||||
string value = JavaScriptConvert.SerializeObject(new GetOnlyPropertyClass());
|
||||
|
||||
GetOnlyPropertyClass c = JavaScriptConvert.DeserializeObject<GetOnlyPropertyClass>(value);
|
||||
|
||||
Assert.AreEqual(c.Field, "Field");
|
||||
Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
|
||||
}
|
||||
|
||||
public class SetOnlyPropertyClass
|
||||
{
|
||||
public string Field = "Field";
|
||||
|
||||
public string SetOnlyProperty
|
||||
{
|
||||
set { }
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SerializeDeserializeSetOnlyProperty()
|
||||
{
|
||||
string value = JavaScriptConvert.SerializeObject(new SetOnlyPropertyClass());
|
||||
|
||||
SetOnlyPropertyClass c = JavaScriptConvert.DeserializeObject<SetOnlyPropertyClass>(value);
|
||||
|
||||
Assert.AreEqual(c.Field, "Field");
|
||||
}
|
||||
|
||||
public class JsonIgnoreAttributeTestClass
|
||||
{
|
||||
private int _property = 21;
|
||||
private int _ignoredProperty = 12;
|
||||
|
||||
public int Field;
|
||||
public int Property
|
||||
{
|
||||
get { return _property; }
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public int IgnoredField;
|
||||
|
||||
[JsonIgnore]
|
||||
public int IgnoredProperty
|
||||
{
|
||||
get { return _ignoredProperty; }
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JsonIgnoreAttributeTest()
|
||||
{
|
||||
string json = JavaScriptConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
|
||||
|
||||
Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
|
||||
|
||||
JsonIgnoreAttributeTestClass c = JavaScriptConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1}");
|
||||
|
||||
Assert.AreEqual(0, c.IgnoredField);
|
||||
Assert.AreEqual(99, c.Field);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GoogleSearchAPI()
|
||||
{
|
||||
string json = @"{
|
||||
results:
|
||||
[
|
||||
{
|
||||
GsearchResultClass:""GwebSearch"",
|
||||
unescapedUrl : ""http://www.google.com/"",
|
||||
url : ""http://www.google.com/"",
|
||||
visibleUrl : ""www.google.com"",
|
||||
cacheUrl :
|
||||
""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
|
||||
title : ""Google"",
|
||||
titleNoFormatting : ""Google"",
|
||||
content : ""Enables users to search the Web, Usenet, and
|
||||
images. Features include PageRank, caching and translation of
|
||||
results, and an option to find similar pages.""
|
||||
},
|
||||
{
|
||||
GsearchResultClass:""GwebSearch"",
|
||||
unescapedUrl : ""http://news.google.com/"",
|
||||
url : ""http://news.google.com/"",
|
||||
visibleUrl : ""news.google.com"",
|
||||
cacheUrl :
|
||||
""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
|
||||
title : ""Google News"",
|
||||
titleNoFormatting : ""Google News"",
|
||||
content : ""Aggregated headlines and a search engine of many of the world's news sources.""
|
||||
},
|
||||
|
||||
{
|
||||
GsearchResultClass:""GwebSearch"",
|
||||
unescapedUrl : ""http://groups.google.com/"",
|
||||
url : ""http://groups.google.com/"",
|
||||
visibleUrl : ""groups.google.com"",
|
||||
cacheUrl :
|
||||
""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
|
||||
title : ""Google Groups"",
|
||||
titleNoFormatting : ""Google Groups"",
|
||||
content : ""Enables users to search and browse the Usenet
|
||||
archives which consist of over 700 million messages, and post new
|
||||
comments.""
|
||||
},
|
||||
|
||||
{
|
||||
GsearchResultClass:""GwebSearch"",
|
||||
unescapedUrl : ""http://maps.google.com/"",
|
||||
url : ""http://maps.google.com/"",
|
||||
visibleUrl : ""maps.google.com"",
|
||||
cacheUrl :
|
||||
""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
|
||||
title : ""Google Maps"",
|
||||
titleNoFormatting : ""Google Maps"",
|
||||
content : ""Provides directions, interactive maps, and
|
||||
satellite/aerial imagery of the United States. Can also search by
|
||||
keyword such as type of business.""
|
||||
}
|
||||
],
|
||||
|
||||
adResults:
|
||||
[
|
||||
{
|
||||
GsearchResultClass:""GwebSearch.ad"",
|
||||
title : ""Gartner Symposium/ITxpo"",
|
||||
content1 : ""Meet brilliant Gartner IT analysts"",
|
||||
content2 : ""20-23 May 2007- Barcelona, Spain"",
|
||||
url :
|
||||
""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="",
|
||||
|
||||
impressionUrl :
|
||||
""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"",
|
||||
|
||||
unescapedUrl :
|
||||
""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="",
|
||||
|
||||
visibleUrl : ""www.gartner.com""
|
||||
}
|
||||
]
|
||||
}
|
||||
";
|
||||
object o = JavaScriptConvert.DeserializeObject(json);
|
||||
string s = string.Empty;
|
||||
s += s;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TorrentDeserializeTest()
|
||||
{
|
||||
string jsonText = @"{
|
||||
"""":"""",
|
||||
""label"": [
|
||||
[""SomeName"",6]
|
||||
],
|
||||
""torrents"": [
|
||||
[""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
|
||||
],
|
||||
""torrentc"": ""1816000723""
|
||||
}";
|
||||
|
||||
JavaScriptObject o = (JavaScriptObject)JavaScriptConvert.DeserializeObject(jsonText);
|
||||
Assert.AreEqual(4, o.Count);
|
||||
|
||||
JavaScriptArray torrentsArray = (JavaScriptArray)o["torrents"];
|
||||
JavaScriptArray nestedTorrentsArray = (JavaScriptArray)torrentsArray[0];
|
||||
Assert.AreEqual(nestedTorrentsArray.Count, 19);
|
||||
}
|
||||
|
||||
public class JsonPropertyClass
|
||||
{
|
||||
[JsonProperty("pie")]
|
||||
public string Pie = "Yum";
|
||||
|
||||
[JsonIgnore]
|
||||
public string pie = "No pie for you!";
|
||||
|
||||
public string pie1 = "PieChart!";
|
||||
|
||||
private int _sweetCakesCount;
|
||||
|
||||
[JsonProperty("sweet_cakes_count")]
|
||||
public int SweetCakesCount
|
||||
{
|
||||
get { return _sweetCakesCount; }
|
||||
set { _sweetCakesCount = value; }
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JsonPropertyClassSerialize()
|
||||
{
|
||||
JsonPropertyClass test = new JsonPropertyClass();
|
||||
test.Pie = "Delicious";
|
||||
test.SweetCakesCount = int.MaxValue;
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeObject(test);
|
||||
|
||||
Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
|
||||
|
||||
JsonPropertyClass test2 = JavaScriptConvert.DeserializeObject<JsonPropertyClass>(jsonText);
|
||||
|
||||
Assert.AreEqual(test.Pie, test2.Pie);
|
||||
Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
|
||||
}
|
||||
|
||||
public class BadJsonPropertyClass
|
||||
{
|
||||
[JsonProperty("pie")]
|
||||
public string Pie = "Yum";
|
||||
|
||||
public string pie = "PieChart!";
|
||||
}
|
||||
|
||||
[Test]
|
||||
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"A member with the name 'pie' already exists on Newtonsoft.Json.Tests.JsonSerializerTest+BadJsonPropertyClass. Use the JsonPropertyAttribute to specify another name.")]
|
||||
public void BadJsonPropertyClassSerialize()
|
||||
{
|
||||
JavaScriptConvert.SerializeObject(new BadJsonPropertyClass());
|
||||
}
|
||||
|
||||
public class Article
|
||||
{
|
||||
public string Name;
|
||||
|
||||
public Article()
|
||||
{
|
||||
}
|
||||
|
||||
public Article(string name)
|
||||
{
|
||||
Name = name;
|
||||
}
|
||||
}
|
||||
|
||||
public class ArticleCollection : List<Article>
|
||||
{
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InheritedListSerialize()
|
||||
{
|
||||
Article a1 = new Article("a1");
|
||||
Article a2 = new Article("a2");
|
||||
|
||||
ArticleCollection articles1 = new ArticleCollection();
|
||||
articles1.Add(a1);
|
||||
articles1.Add(a2);
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeObject(articles1);
|
||||
|
||||
ArticleCollection articles2 = JavaScriptConvert.DeserializeObject<ArticleCollection>(jsonText);
|
||||
|
||||
Assert.AreEqual(articles1.Count, articles2.Count);
|
||||
Assert.AreEqual(articles1[0].Name, articles2[0].Name);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadOnlyCollectionSerialize()
|
||||
{
|
||||
ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(new int[] {0, 1, 2, 3, 4});
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeObject(r1);
|
||||
|
||||
ReadOnlyCollection<int> r2 = JavaScriptConvert.DeserializeObject<ReadOnlyCollection<int>>(jsonText);
|
||||
|
||||
CollectionAssert.AreEqual(r1, r2);
|
||||
}
|
||||
|
||||
//public abstract class Foo
|
||||
//{
|
||||
//}
|
||||
|
||||
//public class Baz : Foo
|
||||
//{
|
||||
//}
|
||||
|
||||
//public class Bar : Foo
|
||||
//{
|
||||
//}
|
||||
|
||||
//public class BazJsonConverter : JsonConverter
|
||||
//{
|
||||
// public override bool CanConvert(Type objectType)
|
||||
// {
|
||||
// throw new Exception("The method or operation is not implemented.");
|
||||
// }
|
||||
//}
|
||||
|
||||
//public class BarJsonConverter : JsonConverter
|
||||
//{
|
||||
// public override bool CanConvert(Type objectType)
|
||||
// {
|
||||
// throw new Exception("The method or operation is not implemented.");
|
||||
// }
|
||||
//}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using Newtonsoft.Json;
|
||||
using System.IO;
|
||||
|
||||
namespace Newtonsoft.Json.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class JsonWriterTest
|
||||
{
|
||||
[Test]
|
||||
public void ValueFormatting()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringWriter sw = new StringWriter(sb);
|
||||
|
||||
using (JsonWriter jsonWriter = new JsonWriter(sw))
|
||||
{
|
||||
jsonWriter.WriteStartArray();
|
||||
jsonWriter.WriteValue('@');
|
||||
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
|
||||
jsonWriter.WriteValue(true);
|
||||
jsonWriter.WriteValue(10);
|
||||
jsonWriter.WriteValue(10.99);
|
||||
jsonWriter.WriteValue(0.99);
|
||||
jsonWriter.WriteValue(0.000000000000000001d);
|
||||
jsonWriter.WriteValue(0.000000000000000001m);
|
||||
jsonWriter.WriteValue(null);
|
||||
jsonWriter.WriteValue("This is a string.");
|
||||
jsonWriter.WriteNull();
|
||||
jsonWriter.WriteUndefined();
|
||||
jsonWriter.WriteEndArray();
|
||||
}
|
||||
|
||||
string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,"""",""This is a string."",null,undefined]";
|
||||
string result = sb.ToString();
|
||||
|
||||
Console.WriteLine("ValueFormatting");
|
||||
Console.WriteLine(result);
|
||||
|
||||
Assert.AreEqual(expected, result);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StringEscaping()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringWriter sw = new StringWriter(sb);
|
||||
|
||||
using (JsonWriter jsonWriter = new JsonWriter(sw))
|
||||
{
|
||||
jsonWriter.WriteStartArray();
|
||||
jsonWriter.WriteValue(@"""These pretzels are making me thirsty!""");
|
||||
jsonWriter.WriteValue("Jeff's house was burninated.");
|
||||
jsonWriter.WriteValue(@"1. You don't talk about fight club.
|
||||
2. You don't talk about fight club.");
|
||||
jsonWriter.WriteValue("35% of\t statistics\n are made\r up.");
|
||||
jsonWriter.WriteEndArray();
|
||||
}
|
||||
|
||||
string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]";
|
||||
string result = sb.ToString();
|
||||
|
||||
Console.WriteLine("StringEscaping");
|
||||
Console.WriteLine(result);
|
||||
|
||||
Assert.AreEqual(expected, result);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Indenting()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringWriter sw = new StringWriter(sb);
|
||||
|
||||
using (JsonWriter jsonWriter = new JsonWriter(sw))
|
||||
{
|
||||
jsonWriter.Formatting = Formatting.Indented;
|
||||
|
||||
jsonWriter.WriteStartObject();
|
||||
jsonWriter.WritePropertyName("CPU");
|
||||
jsonWriter.WriteValue("Intel");
|
||||
jsonWriter.WritePropertyName("PSU");
|
||||
jsonWriter.WriteValue("500W");
|
||||
jsonWriter.WritePropertyName("Drives");
|
||||
jsonWriter.WriteStartArray();
|
||||
jsonWriter.WriteValue("DVD read/writer");
|
||||
jsonWriter.WriteComment("(broken)");
|
||||
jsonWriter.WriteValue("500 gigabyte hard drive");
|
||||
jsonWriter.WriteValue("200 gigabype hard drive");
|
||||
jsonWriter.WriteEnd();
|
||||
jsonWriter.WriteEndObject();
|
||||
}
|
||||
|
||||
string expected = @"{
|
||||
""CPU"": ""Intel"",
|
||||
""PSU"": ""500W"",
|
||||
""Drives"": [
|
||||
""DVD read/writer""
|
||||
/*(broken)*/,
|
||||
""500 gigabyte hard drive"",
|
||||
""200 gigabype hard drive""
|
||||
]
|
||||
}";
|
||||
string result = sb.ToString();
|
||||
|
||||
Console.WriteLine("Indenting");
|
||||
Console.WriteLine(result);
|
||||
|
||||
Assert.AreEqual(expected, result);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void State()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringWriter sw = new StringWriter(sb);
|
||||
|
||||
using (JsonWriter jsonWriter = new JsonWriter(sw))
|
||||
{
|
||||
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
|
||||
|
||||
jsonWriter.WriteStartObject();
|
||||
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
|
||||
|
||||
jsonWriter.WritePropertyName("CPU");
|
||||
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
|
||||
|
||||
jsonWriter.WriteValue("Intel");
|
||||
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
|
||||
|
||||
jsonWriter.WritePropertyName("Drives");
|
||||
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
|
||||
|
||||
jsonWriter.WriteStartArray();
|
||||
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
|
||||
|
||||
jsonWriter.WriteValue("DVD read/writer");
|
||||
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
|
||||
|
||||
jsonWriter.WriteEnd();
|
||||
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
|
||||
|
||||
jsonWriter.WriteEndObject();
|
||||
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>8.0.50727</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{3E6E2335-B079-4B5B-A65A-9D586914BCBB}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Newtonsoft.Json.Tests</RootNamespace>
|
||||
<AssemblyName>Newtonsoft.Json.Tests</AssemblyName>
|
||||
<SccProjectName>
|
||||
</SccProjectName>
|
||||
<SccLocalPath>
|
||||
</SccLocalPath>
|
||||
<SccAuxPath>
|
||||
</SccAuxPath>
|
||||
<SccProvider>
|
||||
</SccProvider>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="nunit.framework, Version=2.4.3.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Lib\nunit.framework.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="AspNetAjaxDateTimeConverterTest.cs" />
|
||||
<Compile Include="JsonReaderTest.cs" />
|
||||
<Compile Include="JsonSerializerTest.cs" />
|
||||
<Compile Include="JsonWriterTest.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="XmlNodeConverterTest.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.csproj">
|
||||
<Project>{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}</Project>
|
||||
<Name>Newtonsoft.Json</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("Newtonsoft Json.NET Test")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Newtonsoft")]
|
||||
[assembly: AssemblyProduct("Newtonsoft Json.NET Test")]
|
||||
[assembly: AssemblyCopyright("Copyright © Newtonsoft 2006")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("0be3d72b-d2ef-409c-985c-d3ede89a25f1")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Revision and Build Numbers
|
||||
// by using the '*' as shown below:
|
||||
[assembly: AssemblyVersion("1.3.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.3.0.0")]
|
||||
@@ -0,0 +1,342 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using NUnit.Framework;
|
||||
using Newtonsoft.Json;
|
||||
using System.IO;
|
||||
using System.Xml;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class XmlNodeConverterTest
|
||||
{
|
||||
[Test]
|
||||
public void DocumentSerializeIndented()
|
||||
{
|
||||
string xml = @"<?xml version=""1.0"" standalone=""no""?>
|
||||
<?xml-stylesheet href=""classic.xsl"" type=""text/xml""?>
|
||||
<span class=""vevent"">
|
||||
<a class=""url"" href=""http://www.web2con.com/"">
|
||||
<span class=""summary"">Web 2.0 Conference<![CDATA[my escaped text]]></span>
|
||||
<abbr class=""dtstart"" title=""2005-10-05"">October 5</abbr>
|
||||
<abbr class=""dtend"" title=""2005-10-08"">7</abbr>
|
||||
<span class=""location"">Argent Hotel, San Francisco, CA</span>
|
||||
</a>
|
||||
</span>";
|
||||
XmlDocument doc = new XmlDocument();
|
||||
doc.LoadXml(xml);
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
|
||||
using (JsonWriter jsonWriter = new JsonWriter(sw))
|
||||
{
|
||||
jsonWriter.Formatting = Formatting.Indented;
|
||||
|
||||
JsonSerializer jsonSerializer = new JsonSerializer();
|
||||
jsonSerializer.Converters.Add(new XmlNodeConverter());
|
||||
|
||||
jsonSerializer.Serialize(jsonWriter, doc);
|
||||
}
|
||||
|
||||
string jsonText = sw.ToString();
|
||||
string expected = @"{
|
||||
""?xml"": {
|
||||
""@version"": ""1.0"",
|
||||
""@standalone"": ""no""
|
||||
},
|
||||
""?xml-stylesheet"": ""href=\""classic.xsl\"" type=\""text/xml\"""",
|
||||
""span"": {
|
||||
""@class"": ""vevent"",
|
||||
""a"": {
|
||||
""@class"": ""url"",
|
||||
""@href"": ""http://www.web2con.com/"",
|
||||
""span"": [
|
||||
{
|
||||
""@class"": ""summary"",
|
||||
""#text"": ""Web 2.0 Conference"",
|
||||
""#cdata-section"": ""my escaped text""
|
||||
},
|
||||
{
|
||||
""@class"": ""location"",
|
||||
""#text"": ""Argent Hotel, San Francisco, CA""
|
||||
}
|
||||
],
|
||||
""abbr"": [
|
||||
{
|
||||
""@class"": ""dtstart"",
|
||||
""@title"": ""2005-10-05"",
|
||||
""#text"": ""October 5""
|
||||
},
|
||||
{
|
||||
""@class"": ""dtend"",
|
||||
""@title"": ""2005-10-08"",
|
||||
""#text"": ""7""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
Assert.AreEqual(expected, jsonText);
|
||||
|
||||
Console.WriteLine("DocumentSerializeIndented");
|
||||
Console.WriteLine(jsonText);
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SerializeNodeTypes()
|
||||
{
|
||||
XmlDocument doc = new XmlDocument();
|
||||
string jsonText;
|
||||
|
||||
Console.WriteLine("SerializeNodeTypes");
|
||||
|
||||
// XmlAttribute
|
||||
XmlAttribute attribute = doc.CreateAttribute("msdata:IsDataSet");
|
||||
attribute.Value = "true";
|
||||
|
||||
jsonText = JavaScriptConvert.SerializeXmlNode(attribute);
|
||||
|
||||
Console.WriteLine(jsonText);
|
||||
Assert.AreEqual(@"{""@msdata:IsDataSet"":""true""}", jsonText);
|
||||
|
||||
|
||||
// XmlProcessingInstruction
|
||||
XmlProcessingInstruction instruction = doc.CreateProcessingInstruction("xml-stylesheet", @"href=""classic.xsl"" type=""text/xml""");
|
||||
|
||||
jsonText = JavaScriptConvert.SerializeXmlNode(instruction);
|
||||
|
||||
Console.WriteLine(jsonText);
|
||||
Assert.AreEqual(@"{""?xml-stylesheet"":""href=\""classic.xsl\"" type=\""text/xml\""""}", jsonText);
|
||||
|
||||
|
||||
// XmlProcessingInstruction
|
||||
XmlCDataSection cDataSection = doc.CreateCDataSection("<Kiwi>true</Kiwi>");
|
||||
|
||||
jsonText = JavaScriptConvert.SerializeXmlNode(cDataSection);
|
||||
|
||||
Console.WriteLine(jsonText);
|
||||
Assert.AreEqual(@"{""#cdata-section"":""<Kiwi>true</Kiwi>""}", jsonText);
|
||||
|
||||
|
||||
// XmlElement
|
||||
XmlElement element = doc.CreateElement("xs:Choice");
|
||||
element.SetAttributeNode(attribute);
|
||||
|
||||
element.AppendChild(instruction);
|
||||
element.AppendChild(cDataSection);
|
||||
|
||||
jsonText = JavaScriptConvert.SerializeXmlNode(element);
|
||||
|
||||
Console.WriteLine(jsonText);
|
||||
Assert.AreEqual(@"{""xs:Choice"":{""@msdata:IsDataSet"":""true"",""?xml-stylesheet"":""href=\""classic.xsl\"" type=\""text/xml\"""",""#cdata-section"":""<Kiwi>true</Kiwi>""}}", jsonText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DocumentFragmentSerialize()
|
||||
{
|
||||
XmlDocument doc = new XmlDocument();
|
||||
|
||||
XmlDocumentFragment fragement = doc.CreateDocumentFragment();
|
||||
|
||||
fragement.InnerXml = "<Item>widget</Item><Item>widget</Item>";
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeXmlNode(fragement);
|
||||
|
||||
string expected = @"{""Item"":[""widget"",""widget""]}";
|
||||
|
||||
Assert.AreEqual(expected, jsonText);
|
||||
|
||||
Console.WriteLine("DocumentFragmentSerialize");
|
||||
Console.WriteLine(jsonText);
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NamespaceSerializeDeserialize()
|
||||
{
|
||||
string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
|
||||
<xs:schema xs:id=""SomeID""
|
||||
xmlns=""""
|
||||
xmlns:xs=""http://www.w3.org/2001/XMLSchema""
|
||||
xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
|
||||
<xs:element name=""MyDataSet"" msdata:IsDataSet=""true"">
|
||||
<xs:complexType>
|
||||
<xs:choice maxOccurs=""unbounded"">
|
||||
<xs:element name=""customers"" >
|
||||
<xs:complexType >
|
||||
<xs:sequence>
|
||||
<xs:element name=""CustomerID"" type=""xs:integer""
|
||||
minOccurs=""0"" />
|
||||
<xs:element name=""CompanyName"" type=""xs:string""
|
||||
minOccurs=""0"" />
|
||||
<xs:element name=""Phone"" type=""xs:string"" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>";
|
||||
|
||||
XmlDocument doc = new XmlDocument();
|
||||
doc.LoadXml(xml);
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeXmlNode(doc);
|
||||
|
||||
XmlDocument deserializedDoc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText);
|
||||
|
||||
Assert.AreEqual(doc.InnerXml, deserializedDoc.InnerXml);
|
||||
|
||||
Console.WriteLine("NamespaceSerializeDeserialize");
|
||||
Console.WriteLine(jsonText);
|
||||
Console.WriteLine(deserializedDoc.InnerXml);
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DocumentDeserialize()
|
||||
{
|
||||
string jsonText = @"{
|
||||
""?xml"": {
|
||||
""@version"": ""1.0"",
|
||||
""@standalone"": ""no""
|
||||
},
|
||||
""span"": {
|
||||
""@class"": ""vevent"",
|
||||
""a"": {
|
||||
""@class"": ""url"",
|
||||
""@href"": ""http://www.web2con.com/"",
|
||||
""span"": {
|
||||
""@class"": ""summary"",
|
||||
""#text"": ""Web 2.0 Conference"",
|
||||
""#cdata-section"": ""my escaped text""
|
||||
}
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
XmlDocument doc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText);
|
||||
|
||||
string expected = @"<?xml version=""1.0"" standalone=""no""?>
|
||||
<span class=""vevent"">
|
||||
<a class=""url"" href=""http://www.web2con.com/"">
|
||||
<span class=""summary"">Web 2.0 Conference<![CDATA[my escaped text]]></span>
|
||||
</a>
|
||||
</span>";
|
||||
|
||||
string formattedXml = GetIndentedInnerXml(doc);
|
||||
|
||||
Console.WriteLine("DocumentDeserialize");
|
||||
Console.WriteLine(formattedXml);
|
||||
Console.WriteLine();
|
||||
|
||||
Assert.AreEqual(expected, formattedXml);
|
||||
}
|
||||
|
||||
private string GetIndentedInnerXml(XmlNode node)
|
||||
{
|
||||
XmlWriterSettings settings = new XmlWriterSettings();
|
||||
settings.Indent = true;
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
|
||||
using (XmlWriter writer = XmlWriter.Create(sw, settings))
|
||||
{
|
||||
node.WriteTo(writer);
|
||||
}
|
||||
|
||||
return sw.ToString();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SingleTextNode()
|
||||
{
|
||||
string xml = @"<?xml version=""1.0"" standalone=""no""?>
|
||||
<root>
|
||||
<person id=""1"">
|
||||
<name>Alan</name>
|
||||
<url>http://www.google.com</url>
|
||||
</person>
|
||||
<person id=""2"">
|
||||
<name>Louis</name>
|
||||
<url>http://www.yahoo.com</url>
|
||||
</person>
|
||||
</root>";
|
||||
|
||||
XmlDocument doc = new XmlDocument();
|
||||
doc.LoadXml(xml);
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeXmlNode(doc);
|
||||
|
||||
XmlDocument newDoc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText);
|
||||
|
||||
Assert.AreEqual(doc.InnerXml, newDoc.InnerXml);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyNode()
|
||||
{
|
||||
string xml = @"<?xml version=""1.0"" standalone=""no""?>
|
||||
<root>
|
||||
<person id=""1"">
|
||||
<name>Alan</name>
|
||||
<url />
|
||||
</person>
|
||||
<person id=""2"">
|
||||
<name>Louis</name>
|
||||
<url>http://www.yahoo.com</url>
|
||||
</person>
|
||||
</root>";
|
||||
|
||||
XmlDocument doc = new XmlDocument();
|
||||
doc.LoadXml(xml);
|
||||
|
||||
string jsonText = JavaScriptConvert.SerializeXmlNode(doc);
|
||||
|
||||
Console.WriteLine(jsonText);
|
||||
|
||||
XmlDocument newDoc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText);
|
||||
|
||||
Assert.AreEqual(doc.InnerXml, newDoc.InnerXml);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OtherElementDataTypes()
|
||||
{
|
||||
string jsonText = @"{""?xml"":{""@version"":""1.0"",""@standalone"":""no""},""root"":{""person"":[{""@id"":""1"",""Float"":2.5,""Integer"":99},{""@id"":""2"",""Boolean"":true,""date"":new Date(954374400000)}]}}";
|
||||
|
||||
XmlDocument newDoc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText);
|
||||
|
||||
string expected = @"<?xml version=""1.0"" standalone=""no""?><root><person id=""1""><Float>2.5</Float><Integer>99</Integer></person><person id=""2""><Boolean>true</Boolean><date>2000-03-30T00:00:00.0000000+12:00</date></person></root>";
|
||||
|
||||
Assert.AreEqual(expected, newDoc.InnerXml);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user