//инициализация public static bool TryCreate(string jsonMessage, out AmazonSesNotification amazonSesNotification) { amazonSesNotification = null; bool result = false; if (string.IsNullOrEmpty(jsonMessage)) return false; try { using (TextReader reader = new StringReader(jsonMessage)) using (var jsonRreader = new Newtonsoft.Json.JsonTextReader(reader)) { var serializer = new Newtonsoft.Json.JsonSerializer(); amazonSesNotification = serializer.Deserialize<AmazonSesNotification>(jsonRreader); } result = true; } catch (Exception ex) { } return result; }
public Message Serialize(OperationDescription operation, MessageVersion version, object[] parameters, object result) { byte[] body; var serializer = new Newtonsoft.Json.JsonSerializer(); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) { //writer.Formatting = Newtonsoft.Json.Formatting.Indented; serializer.Serialize(writer, result); sw.Flush(); body = ms.ToArray(); } } } System.ServiceModel.Channels.Message replyMessage = System.ServiceModel.Channels.Message.CreateMessage(version, operation.Messages[1].Action, new RawBodyWriter(body)); replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw)); var respProp = new HttpResponseMessageProperty(); respProp.Headers[HttpResponseHeader.ContentType] = "application/json"; replyMessage.Properties.Add(HttpResponseMessageProperty.Name, respProp); return replyMessage; }
// private static methods public static Newtonsoft.Json.JsonSerializer CreateWrappedSerializer() { var serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Converters.Add(BsonValueConverter.Instance); serializer.Converters.Add(ObjectIdConverter.Instance); return serializer; }
public override void Up() { var filePath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(new Uri(GetType().Assembly.CodeBase).LocalPath)), "Import201212010811.json"); var serializer = new Newtonsoft.Json.JsonSerializer(); var placeByUserName = serializer.Deserialize <Dictionary<string, string>>(new StreamReader(filePath)); using (var session = DocumentStore.OpenSession()) { var empty = false; var skip = 0; var take = 20; while (!empty) { var result = session.Query<Employee>() .Where(x => x.UserName != null && x.UserName != "") .OrderBy(x => x.UserName) .Skip(skip) .Take(take) .ToArray(); foreach (var employee in result) { string placeKey = null; bool createMenu = false; if (!string.IsNullOrWhiteSpace(employee.UserName) && placeByUserName.TryGetValue(employee.UserName, out placeKey) && placeKey != "-") { createMenu = true; } else if (!string.IsNullOrWhiteSpace(employee.UserName) && !placeByUserName.ContainsKey(employee.UserName)) { if (!string.IsNullOrWhiteSpace(employee.Platform) && (employee.Platform.ToUpper().Contains("MDQ") || employee.Platform.ToUpper().Contains("MDP") || employee.Platform.ToUpper().Contains("MAR"))) { createMenu = true; placeKey = employee.Platform.ToUpper().Contains("GARAY") ? "place_garay" : employee.Platform.ToUpper().Contains("RIOJA") ? "place_larioja" : null; } } if (createMenu) { var employeeMenu = new EmployeeMenu() { Id = "Menu/" + employee.UserName, MenuId = "Menu/DefaultMenu", UserName = employee.UserName, EmployeeName = string.Format("{0}, {1}", employee.LastName, employee.FirstName), DefaultPlaceKey = placeKey, WeeklyChoices = new WeekDayKeyedCollection<EmployeeMenuItem>(), Overrides = new List<EmployeeMenuOverrideItem>() }; session.Store(employeeMenu); } } empty = result.Length == 0; skip += take; } session.SaveChanges(); } }
public ISerializationContextInfo GetSerializationContextInfo(ISerializer serializer, object model, object data, ISerializationConfiguration configuration) { var jsonSerializer = new Newtonsoft.Json.JsonSerializer(); jsonSerializer.ContractResolver = new CatelJsonContractResolver(); jsonSerializer.Converters.Add(new CatelJsonConverter((IJsonSerializer)serializer, configuration)); return new JsonSerializationContextInfo(jsonSerializer, null, null); }
/// <summary> /// Serialize the object into a byte array /// </summary> /// <param name="obj">Object to serialize</param> /// <returns>Byte array to send in the request body</returns> public byte[] Serialize(object obj) { var serializer = new Newtonsoft.Json.JsonSerializer(); ConfigureSerializer(serializer); var output = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(output)) serializer.Serialize(writer, obj); return output.ToArray(); }
public void Deserialize(OperationDescription operation, Dictionary<string, int> parameterNames, Message message, object[] parameters) { object bodyFormatProperty; if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) || (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw) { throw new InvalidOperationException( "Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?"); } var bodyReader = message.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); byte[] rawBody = bodyReader.ReadContentAsBase64(); using (var ms = new MemoryStream(rawBody)) using (var sr = new StreamReader(ms)) { var serializer = new Newtonsoft.Json.JsonSerializer(); if (parameters.Length == 1) { // single parameter, assuming bare parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type); } else { // multiple parameter, needs to be wrapped Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr); reader.Read(); if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject) { throw new InvalidOperationException("Input needs to be wrapped in an object"); } reader.Read(); while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName) { var parameterName = reader.Value as string; reader.Read(); if (parameterNames.ContainsKey(parameterName)) { int parameterIndex = parameterNames[parameterName]; parameters[parameterIndex] = serializer.Deserialize(reader, operation.Messages[0].Body.Parts[parameterIndex].Type); } else { reader.Skip(); } reader.Read(); } reader.Close(); } sr.Close(); ms.Close(); } }
/// <summary> /// Stream an IObject to JSON /// </summary> /// <param name="stream">the stream to serialize the object to</param> /// <param name="o">the oject to be serialized</param> public void Stream( System.IO.StreamWriter stream, IObject o ) { try { Newtonsoft.Json.JsonWriter jw = new Newtonsoft.Json.JsonTextWriter(stream); jw.Formatting = Newtonsoft.Json.Formatting.Indented; var js = new Newtonsoft.Json.JsonSerializer(); js.Serialize(jw, o); } catch (Exception) { throw new NotImplementedException("Method Stream not yet implemented for objects like \"" + o.Name + "\" of class \"SimpleObject\""); } }
public void ProcessRequest(System.Web.HttpContext context) { context.Response.ContentType = "application/json"; Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(context.Response.Output); Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer(); using (System.Data.DataTable dt = Basic_SQL.SQL.GetDataTable("SELECT COL_Hex FROM T_SYS_ApertureColorToHex ORDER BY COL_Aperture")) { jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; ser.Serialize(jsonWriter, dt); jsonWriter.Flush(); } // End Using dt }
public virtual void Write(Entry e, int deep) { writer.WriteLine(); for (int i = 0; i < deep; ++i) writer.Write("\t"); var str = new StringWriter(); var jsonSer = new Newtonsoft.Json.JsonSerializer(); jsonSer.Serialize(str, e.Properties); writer.WriteLine("{{ description: '{0}', offset: {1:0.000}, duration: {2:0.000}, severity: {3}, properties: {4}, entries: [", e.Description, e.Offset, e.Duration, e.Severity, str.ToString()); foreach (Entry s in e.Entries) { Write(s, deep + 1); } writer.WriteLine("]}}"); }
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters) { byte[] body; Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); using (MemoryStream ms = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8)) { using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) { writer.Formatting = Newtonsoft.Json.Formatting.Indented; if (parameters.Length == 1) { // Single parameter, assuming bare serializer.Serialize(sw, parameters[0]); } else { writer.WriteStartObject(); for (int i = 0; i < this.operation.Messages[0].Body.Parts.Count; i++) { writer.WritePropertyName(this.operation.Messages[0].Body.Parts[i].Name); serializer.Serialize(writer, parameters[0]); } writer.WriteEndObject(); } writer.Flush(); sw.Flush(); body = ms.ToArray(); } } } Message requestMessage = Message.CreateMessage(messageVersion, operation.Messages[0].Action, new RawBodyWriter(body)); requestMessage.Headers.To = operationUri; requestMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw)); HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty(); reqProp.Headers[HttpRequestHeader.ContentType] = "application/json"; requestMessage.Properties.Add(HttpRequestMessageProperty.Name, reqProp); return requestMessage; }
public Notification Parse(string data) { string msg = string.Empty; string custom = string.Empty; try { var reader = new Newtonsoft.Json.JsonTextReader (new StringReader(data)); var serializer = new Newtonsoft.Json.JsonSerializer (); var obj = serializer.Deserialize<NotificationObject> (reader); msg = obj.title; custom = obj.u; } catch (Exception ex) { MvxTrace.Error ("Failed to parse incoming data: {0}", ex.Message); } return new Notification (msg, data, custom); }
public override void Up() { var filePath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(new Uri(GetType().Assembly.CodeBase).LocalPath)), "Import201210171646.json"); var serializer = new Newtonsoft.Json.JsonSerializer(); var data = serializer.Deserialize<ImportItem[]>(new StreamReader(filePath)).ToDictionary(x => new ImportKey(x)); using (var session = DocumentStore.OpenSession()) { var empty = false; var skip = 0; var take = 20; while (!empty) { var result = session.Query<Employee>() .OrderBy(x => x.LastName).ThenBy(x => x.FirstName) .Skip(skip) .Take(take) .ToArray(); foreach (var employee in result) { ImportItem item; if (data.TryGetValue(new ImportKey(employee), out item)) { if (!string.IsNullOrWhiteSpace(item.RealLastName)) employee.LastName = item.RealLastName; if (!string.IsNullOrWhiteSpace(item.RealFirstName)) employee.FirstName = item.RealFirstName; if (!string.IsNullOrWhiteSpace(item.Email)) employee.CorporativeEmail = item.Email; if (!string.IsNullOrWhiteSpace(item.DomainUser)) employee.UserName = item.DomainUser; } } empty = result.Length == 0; skip += take; } session.SaveChanges(); } }
public object DeserializeReply(Message message, object[] parameters) { object bodyFormatProperty; if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) || (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw) { throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?"); } XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); bodyReader.ReadStartElement("Binary"); byte[] body = bodyReader.ReadContentAsBase64(); using (MemoryStream ms = new MemoryStream(body)) { using (StreamReader sr = new StreamReader(ms)) { Type returnType = this.operation.Messages[1].Body.ReturnValue.Type; return serializer.Deserialize(sr, returnType); } } }
protected override void Send(ManagementReport report, String activityId, String agentId) { var reportJson = new Dictionary<String, Object>{ {"ID", report.ID}, {"SourceID", report.SourceID }, {"DateTime", report.DateTime}, {"State", new Dictionary<String, Object> { {"Health", report.State.Health.ToString() }, {"Execution", report.State.Execution.ToString()}, {"Failures", (from f in report.State.Failures select new Dictionary<String, Object> { {"FailureID", f.FailureID}, {"SourceID", f.SourceID}, {"Details", f.Details} }).ToArray()} }}, {"Metrics", report.Metrics != null ? (from m in report.Metrics select new Dictionary<String, Object> { {"MetricID", m.MetricID}, {"SourceID", m.SourceID}, {"Reference", m.Reference}, {"Value", m.Value}, {"Details", m.Details}, {"CategoryID", m.CategoryID}, {"DateTime", m.DateTime } }).ToArray() : null}, {"ActivityID", activityId}, {"AgentID", agentId}, }; var str = new StringWriter(); var jsonSer = new Newtonsoft.Json.JsonSerializer(); jsonSer.Serialize(str, reportJson); NetBrokerMessage brokerMessage = new NetBrokerMessage(str.ToString()); this.brokerClient.Publish(brokerMessage, this.topic); }
/// <summary> /// 发送HTTP请求 /// </summary> /// <param name="url">请求的URL</param> /// <param name="param">请求的参数</param> /// <returns>请求结果</returns> public static string request(string url, string param) { string strURL = url + '?' + param; System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); request.Method = "GET"; // 添加header request.Headers.Add("apikey", "ec3dedf550e5e6cea6c53385ed4f474a"); System.Net.HttpWebResponse response; response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream s; s = response.GetResponseStream(); string StrDate = ""; string strValue = ""; StreamReader Reader = new StreamReader(s, Encoding.UTF8); while ((StrDate = Reader.ReadLine()) != null) { strValue += StrDate + "\r\n"; } StringReader sr = new StringReader(strValue); Newtonsoft.Json.JsonTextReader jsonReader = new Newtonsoft.Json.JsonTextReader(sr); Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); var r = serializer.Deserialize<Resault>(jsonReader); //txtResult.Text = r.trans_result[0].dst; if (r.retData.trans_result != null) { strValue = r.retData.trans_result[0].dst; } else { strValue = ""; } //StringReader sr=new //Newtonsoft.Json.JsonConverter. return strValue; }
public UnionInNestedNSUnion ReadJson(Newtonsoft.Json.JsonReader reader, UnionInNestedNSUnion _o, Newtonsoft.Json.JsonSerializer serializer) { if (_o == null) { return(null); } switch (_o.Type) { default: break; case UnionInNestedNS.TableInNestedNS: _o.Value = serializer.Deserialize <NamespaceA.NamespaceB.TableInNestedNST>(reader); break; } return(_o); }
public void NewtonsoftJsonSerializeDeserializeBenchmark() { var serializer = new Newtonsoft.Json.JsonSerializer() { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, }; int runs = 50000; DateTime start, stop; MessageModel msg = null; start = DateTime.UtcNow; for (int i = 0; i < runs; i++) { var writer = new StringWriter(); serializer.Serialize(writer, SimpleMessage); var reader = new StringReader(writer.ToString()); var jsonReader = new Newtonsoft.Json.JsonTextReader(reader); var dtoMsg = serializer.Deserialize<MessageDtoModelV1>(jsonReader); } stop = DateTime.UtcNow; Assert.AreEqual(ComplexMessage, msg); var total = (stop - start).TotalMilliseconds; Console.WriteLine( "NewtonsoftJsonSerialize+Deserialize(Simple): avg: {0:0.00} ms runs: {1} took: {2:0.00} ms", total / runs, runs, total ); start = DateTime.UtcNow; for (int i = 0; i < runs; i++) { var writer = new StringWriter(); serializer.Serialize(writer, ComplexMessage); var reader = new StringReader(writer.ToString()); var jsonReader = new Newtonsoft.Json.JsonTextReader(reader); var dtoMsg = serializer.Deserialize<MessageDtoModelV1>(jsonReader); } stop = DateTime.UtcNow; Assert.AreEqual(ComplexMessage, msg); total = (stop - start).TotalMilliseconds; Console.WriteLine( "NewtonsoftJsonSerialize+Deserialize(ComplexMessage): avg: {0:0.00} ms runs: {1} took: {2:0.00} ms", total / runs, runs, total ); }
public void BenchmarkJson() { var dateTime = DateTime.Parse("2015-09-16T11:43:50.8355302-04:00"); var guid = Guid.Parse("862663f1-3dd1-46c2-97d5-f9034b784854"); var foo = new Foo { Corge = "abc", Grault = 123.45, Garply = true, Bar = new Bar { Waldo = dateTime, Fred = guid }, Bazes = new List<Baz> { new Baz { Wibble = 2147483647, Wobble = 9223372036854775807, Wubble = 123.45M }, new Baz { Wibble = 0, Wobble = 0, Wubble = 0.5M }, new Baz { Wibble = -2147483648, Wobble = -9223372036854775808, Wubble = -123.45M } } }; var newtonsoftJsonSerializer = new Newtonsoft.Json.JsonSerializer(); var xSerializerJsonSerializer = new JsonSerializer<Foo>(); var newtonsoftJson = NewtonsoftJsonSerialize(newtonsoftJsonSerializer, foo); var xSerializerJson = XSerializerJsonSerialize(xSerializerJsonSerializer, foo); Assert.That(xSerializerJson, Is.EqualTo(newtonsoftJson)); const int iterations = 1000000; var newtonsoftStopwatch = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { NewtonsoftJsonSerialize(newtonsoftJsonSerializer, foo); } newtonsoftStopwatch.Stop(); var xSerializerStopwatch = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { XSerializerJsonSerialize(xSerializerJsonSerializer, foo); } xSerializerStopwatch.Stop(); Console.WriteLine("Serialization"); Console.WriteLine("Newtonsoft Elapsed Time: {0}", newtonsoftStopwatch.Elapsed); Console.WriteLine("XSerializer Elapsed Time: {0}", xSerializerStopwatch.Elapsed); }
public void WriteJson(Newtonsoft.Json.JsonWriter writer, UnionInNestedNSUnion _o, Newtonsoft.Json.JsonSerializer serializer) { if (_o == null) { return; } serializer.Serialize(writer, _o.Value); }
/// <summary> /// Writes the json. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value.</param> /// <param name="serializer">The serializer.</param> public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { if (value.GetType() != typeof(DateTime)) { throw new ArgumentOutOfRangeException("value", "The value provided was not the expected data type."); } writer.WriteValue(((DateTime)value).ToString(DateFormat, CultureInfo.InvariantCulture)); }
/// <summary> /// Reads the JSON representation of the object. /// </summary> public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { if (typeof(DataService.Attribute) == objectType) { var result = default(DataService.Attribute); if (reader.Read() && reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName) { var key = ushort.Parse(reader.Value.ToString(), System.Globalization.CultureInfo.InvariantCulture); var value = reader.ReadAsString(); result = new DataService.Attribute(key, value); } return(result); } else { var result = new List <DataService.Attribute>(); if (reader.TokenType == Newtonsoft.Json.JsonToken.StartObject) { while (reader.Read() && reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName) { var key = ushort.Parse(reader.Value.ToString(), System.Globalization.CultureInfo.InvariantCulture); var value = reader.ReadAsString(); result.Add(new DataService.Attribute(key, value)); } } return(result.ToArray()); } }
public void DeserializeRequest(Message message, object[] parameters) { object bodyFormatProperty; if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) || (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw) { throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?"); } var bodyReader = message.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); var rawBody = bodyReader.ReadContentAsBase64(); var ms = new MemoryStream(rawBody); var sr = new StreamReader(ms); var serializer = new Newtonsoft.Json.JsonSerializer(); if (parameters.Length == 1) { // single parameter, assuming bare parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type); } else { // multiple parameter, needs to be wrapped Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr); reader.Read(); if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject) { throw new InvalidOperationException("Input needs to be wrapped in an object"); } reader.Read(); while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName) { var parameterName = reader.Value as string; reader.Read(); if (parameterNames.ContainsKey(parameterName)) { var parameterIndex = parameterNames[parameterName]; parameters[parameterIndex] = serializer.Deserialize(reader, operation.Messages[0].Body.Parts[parameterIndex].Type); } else { reader.Skip(); } reader.Read(); } //Attach parameters retrieved from the Uri var templateMatchResults = (UriTemplateMatch)message.Properties["UriTemplateMatchResults"]; foreach (var parameterName in parameterNames.Where(parameterName => parameters[parameterName.Value] == null)) { if(templateMatchResults.BoundVariables.AllKeys.Contains(parameterName.Key.ToUpper())) parameters[parameterName.Value] = templateMatchResults.BoundVariables[parameterName.Key.ToUpper()]; } reader.Close(); } sr.Close(); ms.Close(); }
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { writer.WriteValue(((EventTarget)value).Id); }
public void BenchmarkJson() { var dateTime = DateTime.Parse("2015-09-16T11:43:50.8355302-04:00"); var guid = Guid.Parse("862663f1-3dd1-46c2-97d5-f9034b784854"); var foo = new Foo { Corge = "abc", Grault = 123.45, Garply = true, Bar = new Bar { Waldo = dateTime, Fred = guid }, Bazes = new List <Baz> { new Baz { Wibble = 2147483647, Wobble = 9223372036854775807, Wubble = 123.45M }, new Baz { Wibble = 0, Wobble = 0, Wubble = 0.5M }, new Baz { Wibble = -2147483648, Wobble = -9223372036854775808, Wubble = -123.45M } } }; var newtonsoftJsonSerializer = new Newtonsoft.Json.JsonSerializer(); var xSerializerJsonSerializer = new JsonSerializer <Foo>(); var newtonsoftJson = NewtonsoftJsonSerialize(newtonsoftJsonSerializer, foo); var xSerializerJson = XSerializerJsonSerialize(xSerializerJsonSerializer, foo); Assert.That(xSerializerJson, Is.EqualTo(newtonsoftJson)); const int iterations = 1000000; var newtonsoftStopwatch = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { NewtonsoftJsonSerialize(newtonsoftJsonSerializer, foo); } newtonsoftStopwatch.Stop(); var xSerializerStopwatch = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { XSerializerJsonSerialize(xSerializerJsonSerializer, foo); } xSerializerStopwatch.Stop(); Console.WriteLine("Serialization"); Console.WriteLine("Newtonsoft Elapsed Time: {0}", newtonsoftStopwatch.Elapsed); Console.WriteLine("XSerializer Elapsed Time: {0}", xSerializerStopwatch.Elapsed); }
protected override void ConfigureSerializer(Newtonsoft.Json.JsonSerializer serializer) { base.ConfigureSerializer(serializer); serializer.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; }
/// <summary> /// Creates a temporary verification file. /// </summary> /// <returns>The verification file.</returns> /// <param name="db">The database instance</param> /// <param name="stream">The stream to write to</param> public static void CreateVerificationFile(LocalDatabase db, System.IO.StreamWriter stream) { var s = new Newtonsoft.Json.JsonSerializer(); s.Serialize(stream, db.GetRemoteVolumes().Cast <IRemoteVolume>().ToArray()); }
/// <summary> /// Writes the JSON representation of the object. /// </summary> public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { var attribute = value as DataService.Attribute; if (attribute != null) { writer.WritePropertyName(attribute.Key.ToString(System.Globalization.CultureInfo.InvariantCulture)); writer.WriteValue(attribute.Value); } else { writer.WriteStartObject(); var attributes = (DataService.Attribute[])value; if (attributes != null && attributes.Length > 0) { foreach (var att in attributes) { writer.WritePropertyName(att.Key.ToString(System.Globalization.CultureInfo.InvariantCulture)); writer.WriteValue(att.Value); } } writer.WriteEndObject(); } }
private void SerializeJsonNetBinaryBenchInner(object o, MemoryStream ms) { for (int i = 0; i < Iterations; i++) { var s = new Newtonsoft.Json.JsonSerializer(); var w = new BsonWriter(ms); s.Serialize(w, o); Escape(w); w.Flush(); } }
public PhotonJsonNetSerializer() { this.serializer = new Newtonsoft.Json.JsonSerializer(); }
public static int Main(string[] _args) { var args = new List<string>(_args); var opts = Duplicati.Library.Utility.CommandLineParser.ExtractOptions(args); string inputfolder; string outputfolder; string keyfile; string manifestfile; string keyfilepassword; string gpgkeyfile; string gpgpath; opts.TryGetValue("input", out inputfolder); opts.TryGetValue("output", out outputfolder); opts.TryGetValue("keyfile", out keyfile); opts.TryGetValue("manifest", out manifestfile); opts.TryGetValue("keyfile-password", out keyfilepassword); opts.TryGetValue("gpgkeyfile", out gpgkeyfile); opts.TryGetValue("gpgpath", out gpgpath); var usedoptions = new string[] { "input", "output", "keyfile", "manifest", "keyfile-password", "gpgkeyfile", "gpgpath" }; if (string.IsNullOrWhiteSpace(inputfolder)) { Console.WriteLine("Missing input folder"); return 4; } if (string.IsNullOrWhiteSpace(outputfolder)) { Console.WriteLine("Missing output folder"); return 4; } if (string.IsNullOrWhiteSpace(keyfile)) { Console.WriteLine("Missing keyfile"); return 4; } if (!System.IO.Directory.Exists(inputfolder)) { Console.WriteLine("Input folder not found"); return 4; } if (string.IsNullOrWhiteSpace(keyfilepassword)) { Console.WriteLine("Enter keyfile passphrase: "); keyfilepassword = Console.ReadLine().Trim(); } if (!System.IO.File.Exists(keyfile)) { Console.WriteLine("Keyfile not found, creating new"); var newkey = System.Security.Cryptography.RSACryptoServiceProvider.Create().ToXmlString(true); using (var enc = new Duplicati.Library.Encryption.AESEncryption(keyfilepassword, new Dictionary<string, string>())) using (var fs = System.IO.File.OpenWrite(keyfile)) using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(newkey))) enc.Encrypt(ms, fs); } if (!System.IO.Directory.Exists(outputfolder)) System.IO.Directory.CreateDirectory(outputfolder); var privkey = (System.Security.Cryptography.RSACryptoServiceProvider)System.Security.Cryptography.RSACryptoServiceProvider.Create(); using(var enc = new Duplicati.Library.Encryption.AESEncryption(keyfilepassword, new Dictionary<string, string>())) using(var ms = new System.IO.MemoryStream()) using(var fs = System.IO.File.OpenRead(keyfile)) { enc.Decrypt(fs, ms); ms.Position = 0; using(var sr = new System.IO.StreamReader(ms)) privkey.FromXmlString(sr.ReadToEnd()); } if (Duplicati.Library.AutoUpdater.AutoUpdateSettings.SignKey == null || privkey.ToXmlString(false) != Duplicati.Library.AutoUpdater.AutoUpdateSettings.SignKey.ToXmlString(false)) { Console.WriteLine("The public key in the project is not the same as the public key from the file"); Console.WriteLine("Try setting the key to: "); Console.WriteLine(privkey.ToXmlString(false)); return 5; } string gpgkeyid = null; string gpgkeypassphrase = null; if (string.IsNullOrWhiteSpace(gpgkeyfile)) { Console.WriteLine("No gpgfile, skipping GPG signature files"); } else if (!System.IO.File.Exists(gpgkeyfile)) { Console.WriteLine("Missing gpgfile"); return 6; } else { using(var enc = new Duplicati.Library.Encryption.AESEncryption(keyfilepassword, new Dictionary<string, string>())) using(var ms = new System.IO.MemoryStream()) using(var fs = System.IO.File.OpenRead(gpgkeyfile)) { enc.Decrypt(fs, ms); ms.Position = 0; // No real format, just two lines using (var sr = new System.IO.StreamReader(ms)) { var lines = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); gpgkeyid = lines[0]; gpgkeypassphrase = lines[1]; } } } Duplicati.Library.AutoUpdater.UpdateInfo updateInfo; using (var fs = System.IO.File.OpenRead(manifestfile)) using (var sr = new System.IO.StreamReader(fs)) using (var jr = new Newtonsoft.Json.JsonTextReader(sr)) updateInfo = new Newtonsoft.Json.JsonSerializer().Deserialize<Duplicati.Library.AutoUpdater.UpdateInfo>(jr); var isopts = new Dictionary<string, string>(opts, StringComparer.InvariantCultureIgnoreCase); foreach (var usedopt in usedoptions) isopts.Remove(usedopt); foreach (var k in updateInfo.GetType().GetFields()) if (isopts.ContainsKey(k.Name)) { try { //Console.WriteLine("Setting {0} to {1}", k.Name, isopts[k.Name]); if (k.FieldType == typeof(string[])) k.SetValue(updateInfo, isopts[k.Name].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); else if (k.FieldType == typeof(Version)) k.SetValue(updateInfo, new Version(isopts[k.Name])); else if (k.FieldType == typeof(int)) k.SetValue(updateInfo, int.Parse(isopts[k.Name])); else if (k.FieldType == typeof(long)) k.SetValue(updateInfo, long.Parse(isopts[k.Name])); else k.SetValue(updateInfo, isopts[k.Name]); } catch (Exception ex) { Console.WriteLine("Failed setting {0} to {1}: {2}", k.Name, isopts[k.Name], ex.Message); } isopts.Remove(k.Name); } foreach(var opt in isopts) Console.WriteLine("Warning! unused option: {0} = {1}", opt.Key, opt.Value); using (var tf = new Duplicati.Library.Utility.TempFile()) { using (var fs = System.IO.File.OpenWrite(tf)) using (var tw = new System.IO.StreamWriter(fs)) new Newtonsoft.Json.JsonSerializer().Serialize(tw, updateInfo); Duplicati.Library.AutoUpdater.UpdaterManager.CreateUpdatePackage(privkey, inputfolder, outputfolder, tf); } if (gpgkeyid != null) { gpgpath = gpgpath ?? "gpg"; var srcfile = System.IO.Path.Combine(outputfolder, "package.zip"); var proc = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = gpgpath, Arguments = string.Format("--passphrase-fd 0 --batch --yes --default-key={1} --output \"{0}.sig\" --detach-sig \"{0}\"", srcfile, gpgkeyid), RedirectStandardInput = true, UseShellExecute = false }); proc.StandardInput.WriteLine(gpgkeypassphrase); proc.WaitForExit(); proc = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = gpgpath, Arguments = string.Format("--passphrase-fd 0 --batch --yes --default-key={1} --armor --output \"{0}.sig.asc\" --detach-sig \"{0}\"", srcfile, gpgkeyid), RedirectStandardInput = true, UseShellExecute = false }); proc.StandardInput.WriteLine(gpgkeypassphrase); proc.WaitForExit(); } return 0; }
static async Task Main(string[] args) { // create an object graph var people = new List <Person> { new Person(30000M) { FirstName = "Alice", LastName = "Smith", DateOfBirth = new DateTime(1974, 3, 14) }, new Person(40000M) { FirstName = "Bob", LastName = "Jones", DateOfBirth = new DateTime(1969, 11, 23) }, new Person(20000M) { FirstName = "Charlie", LastName = "Cox", DateOfBirth = new DateTime(1984, 5, 4), Children = new HashSet <Person> { new Person(0M) { FirstName = "Sally", LastName = "Cox", DateOfBirth = new DateTime(2000, 7, 12) } } } }; // create an object that will format a List of Persons as XML var xs = new XmlSerializer(typeof(List <Person>)); // create a file to write to string path = Combine(CurrentDirectory, "people.xml"); using (FileStream stream = File.Create(path)) { // serialize the object graph to the stream xs.Serialize(stream, people); } WriteLine($"Written {new FileInfo(path).Length:N0} bytes of XML to {path}"); WriteLine(); // display the serialized object graph WriteLine(File.ReadAllText(path)); // Open the xml file and deserialize it using (FileStream xmlLoad = File.Open(path, FileMode.Open)) { // deserialize and cast the object graph into a List of Person var loadedPeople = (List <Person>)xs.Deserialize(xmlLoad); foreach (var item in loadedPeople) { WriteLine($"{item.LastName} has {item.Children.Count} children."); } } // create a file to write to using JSON string jsonPath = Combine(CurrentDirectory, "people.json"); using (StreamWriter jsonStream = File.CreateText(jsonPath)) { // create an object that will format as JSON var jss = new Newtonsoft.Json.JsonSerializer(); // serialize the object graph into a string jss.Serialize(jsonStream, people); } WriteLine(); WriteLine($"Written {new FileInfo(jsonPath).Length:N0} bytes of JSON to: {jsonPath}"); // display the serialized object graph WriteLine(File.ReadAllText(jsonPath)); using (FileStream jsonLoad = File.Open(jsonPath, FileMode.Open)) { // deserialize object graph into a List of Person var loadedPeople = (List <Person>) await NuJson.DeserializeAsync(utf8Json : jsonLoad, returnType : typeof(List <Person>)); foreach (var item in loadedPeople) { WriteLine($"{item.LastName} has {item.Children?.Count} children."); } } }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { throw new NotSupportedException(); }
private void SetExceptionFieldValue(Newtonsoft.Json.Linq.JObject jObject, string propertyName, object value, string fieldName, Newtonsoft.Json.Serialization.IContractResolver resolver, Newtonsoft.Json.JsonSerializer serializer) { var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(System.Exception)).GetDeclaredField(fieldName); var jsonPropertyName = resolver is Newtonsoft.Json.Serialization.DefaultContractResolver ? ((Newtonsoft.Json.Serialization.DefaultContractResolver)resolver).GetResolvedPropertyName(propertyName) : propertyName; if (jObject[jsonPropertyName] != null) { var fieldValue = jObject[jsonPropertyName].ToObject(field.FieldType, serializer); field.SetValue(value, fieldValue); } }
private void Invoke(int id) { Cnljli.Utility.HttpUtility.Request((e) => { this.BeginInvoke(() => { IsIndeterminate = false; LoadText = "网络错误,请检查网络"; }); }, (str) => { Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(str)); CommentModel<Comment> deserializedProduct = new Newtonsoft.Json.JsonSerializer().Deserialize<CommentModel<Comment>>(reader); this.BeginInvoke(() => { if (deserializedProduct.appending.Count > 0) { deserializedProduct.appending.ForEach(x => { Appending.Add(x); }); } else { HavAppend = System.Windows.Visibility.Collapsed; } Const.ParstText(string.Format("\t\t{0}", deserializedProduct.article.content)).ForEach(x => { Content.Add(x); }); deserializedProduct.list.ForEach(x => { Comment.Add(x); }); Title = deserializedProduct.article.title; Author = deserializedProduct.article.login; Create = deserializedProduct.article.Post_at; IsLoad = false; }); }, string.Format(Const.Commit, id, 1), Headers); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var jObject = serializer.Deserialize <Newtonsoft.Json.Linq.JObject>(reader); if (jObject == null) { return(null); } var discriminatorValue = jObject.GetValue(_discriminator); var discriminator = discriminatorValue != null?Newtonsoft.Json.Linq.Extensions.Value <string>(discriminatorValue) : null; var subtype = GetObjectSubtype(objectType, discriminator); var objectContract = serializer.ContractResolver.ResolveContract(subtype) as Newtonsoft.Json.Serialization.JsonObjectContract; if (objectContract == null || System.Linq.Enumerable.All(objectContract.Properties, p => p.PropertyName != _discriminator)) { jObject.Remove(_discriminator); } try { _isReading = true; return(serializer.Deserialize(jObject.CreateReader(), subtype)); } finally { _isReading = false; } }
// public methods /// <inheritdoc/> public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var adapter = reader as BsonReaderAdapter; if (adapter != null && adapter.BsonValue != null && adapter.BsonValue.BsonType == BsonType.RegularExpression) { return((BsonRegularExpression)adapter.BsonValue); } switch (reader.TokenType) { case Newtonsoft.Json.JsonToken.Null: return(null); case Newtonsoft.Json.JsonToken.StartObject: return(ReadExtendedJson(reader)); case Newtonsoft.Json.JsonToken.String: return(new BsonRegularExpression((string)reader.Value)); default: var message = string.Format("Error reading BsonRegularExpression. Unexpected token: {0}.", reader.TokenType); throw new Newtonsoft.Json.JsonReaderException(message); } }
// public methods /// <inheritdoc/> public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var adapter = reader as BsonReaderAdapter; if (adapter != null && adapter.BsonValue != null && adapter.BsonValue.BsonType == BsonType.Double) { return((BsonDouble)adapter.BsonValue); } switch (reader.TokenType) { case Newtonsoft.Json.JsonToken.Float: case Newtonsoft.Json.JsonToken.Integer: case Newtonsoft.Json.JsonToken.String: double doubleValue; if (reader.Value is double) { doubleValue = (double)reader.Value; } else { doubleValue = Convert.ToDouble(reader.Value, NumberFormatInfo.InvariantInfo); } return((BsonDouble)doubleValue); case Newtonsoft.Json.JsonToken.Null: return(null); default: var message = string.Format("Error reading BsonDouble. Unexpected token: {0}.", reader.TokenType); throw new Newtonsoft.Json.JsonReaderException(message); } }
/// <summary> /// Reads the json. /// </summary> /// <param name="reader">The reader.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value.</param> /// <param name="serializer">The serializer.</param> /// <returns>The parsed value as a DateTime, or null.</returns> public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { if (reader.Value == null || reader.Value.GetType() != typeof(string)) { return(new DateTime()); } DateTime parsedDate; return(DateTime.TryParseExact( (string)reader.Value, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate) ? parsedDate : new DateTime()); }
/// <inheritdoc/> public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { if (value == null) { writer.WriteNull(); } else { var bsonDouble = (BsonDouble)value; writer.WriteValue(bsonDouble.Value); } }
public void Put(string remotename, System.IO.Stream stream) { if (stream.Length > BITS_FILE_SIZE_LIMIT) { // Get extra info for BITS var uid = UserID; var fid = FolderID.Split('.')[2]; // Create a session var url = string.Format("https://cid-{0}.users.storage.live.com/items/{1}/{2}?access_token={3}", uid, fid, Utility.Uri.UrlPathEncode(remotename), Library.Utility.Uri.UrlEncode(m_oauth.AccessToken)); var req = (HttpWebRequest)WebRequest.Create(url); req.UserAgent = USER_AGENT; req.Method = "POST"; req.ContentType = "application/json"; req.Headers.Add("X-Http-Method-Override", "BITS_POST"); req.Headers.Add("BITS-Packet-Type", "Create-Session"); req.Headers.Add("BITS-Supported-Protocols", "{7df0354d-249b-430f-820d-3d2a9bef4931}"); req.ContentLength = 0; var areq = new Utility.AsyncHttpRequest(req); string sessionid; using(var resp = (HttpWebResponse)areq.GetResponse()) { var packtype = resp.Headers["BITS-Packet-Type"]; if (!packtype.Equals("Ack", StringComparison.InvariantCultureIgnoreCase)) throw new Exception(string.Format("Unable to create BITS transfer, got status: {0}", packtype)); sessionid = resp.Headers["BITS-Session-Id"]; } if (string.IsNullOrEmpty(sessionid)) throw new Exception("BITS session-id was missing"); // Session is now created, start uploading chunks var offset = 0L; var retries = 0; while (offset < stream.Length) { try { var bytesInChunk = Math.Min(BITS_CHUNK_SIZE, stream.Length - offset); req = (HttpWebRequest)WebRequest.Create(url); req.UserAgent = USER_AGENT; req.Method = "POST"; req.Headers.Add("X-Http-Method-Override", "BITS_POST"); req.Headers.Add("BITS-Packet-Type", "Fragment"); req.Headers.Add("BITS-Session-Id", sessionid); req.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}", offset, offset + bytesInChunk - 1, stream.Length)); req.ContentLength = bytesInChunk; if (stream.Position != offset) stream.Position = offset; areq = new Utility.AsyncHttpRequest(req); var remaining = (int)bytesInChunk; using(var reqs = areq.GetRequestStream()) { int read; while ((read = stream.Read(m_copybuffer, 0, Math.Min(m_copybuffer.Length, remaining))) != 0) { reqs.Write(m_copybuffer, 0, read); remaining -= read; } } using(var resp = (HttpWebResponse)areq.GetResponse()) { if (resp.StatusCode != HttpStatusCode.OK) throw new WebException("Invalid partial upload response", null, WebExceptionStatus.UnknownError, resp); } offset += bytesInChunk; retries = 0; } catch (Exception ex) { var retry = false; // If we get a 5xx error, or some network issue, we retry if (ex is WebException && ((WebException)ex).Response is HttpWebResponse) { var code = (int)((HttpWebResponse)((WebException)ex).Response).StatusCode; retry = code >= 500 && code <= 599; } else if (ex is System.Net.Sockets.SocketException || ex is System.IO.IOException || ex.InnerException is System.Net.Sockets.SocketException || ex.InnerException is System.IO.IOException) { retry = true; } // Retry with exponential backoff if (retry && retries < 5) { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(Math.Pow(2, retries))); retries++; } else throw; } } // Transfer completed, now commit the upload and close the session req = (HttpWebRequest)WebRequest.Create(url); req.UserAgent = USER_AGENT; req.Method = "POST"; req.Headers.Add("X-Http-Method-Override", "BITS_POST"); req.Headers.Add("BITS-Packet-Type", "Close-Session"); req.Headers.Add("BITS-Session-Id", sessionid); req.ContentLength = 0; areq = new Utility.AsyncHttpRequest(req); using(var resp = (HttpWebResponse)areq.GetResponse()) { if (resp.StatusCode != HttpStatusCode.OK) throw new Exception("Invalid partial upload commit response"); } } else { var url = string.Format("{0}/{1}/files/{2}?access_token={3}", WLID_SERVER, FolderID, Utility.Uri.UrlPathEncode(remotename), Library.Utility.Uri.UrlEncode(m_oauth.AccessToken)); var req = (HttpWebRequest)WebRequest.Create(url); req.UserAgent = USER_AGENT; req.Method = "PUT"; try { req.ContentLength = stream.Length; } catch { } // Docs says not to set this ? //req.ContentType = "application/octet-stream"; var areq = new Utility.AsyncHttpRequest(req); using(var reqs = areq.GetRequestStream()) Utility.Utility.CopyStream(stream, reqs, true, m_copybuffer); using(var resp = (HttpWebResponse)areq.GetResponse()) using(var rs = areq.GetResponseStream()) using(var tr = new System.IO.StreamReader(rs)) using(var jr = new Newtonsoft.Json.JsonTextReader(tr)) { var nf = new Newtonsoft.Json.JsonSerializer().Deserialize<WLID_FolderItem>(jr); m_fileidCache[remotename] = nf.id; } } }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var jObject = serializer.Deserialize <Newtonsoft.Json.Linq.JObject>(reader); if (jObject == null) { return(null); } var newSerializer = new Newtonsoft.Json.JsonSerializer(); newSerializer.ContractResolver = (Newtonsoft.Json.Serialization.IContractResolver)System.Activator.CreateInstance(serializer.ContractResolver.GetType()); var field = GetField(typeof(Newtonsoft.Json.Serialization.DefaultContractResolver), "_sharedCache"); if (field != null) { field.SetValue(newSerializer.ContractResolver, false); } dynamic resolver = newSerializer.ContractResolver; if (System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperty(newSerializer.ContractResolver.GetType(), "IgnoreSerializableAttribute") != null) { resolver.IgnoreSerializableAttribute = true; } if (System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperty(newSerializer.ContractResolver.GetType(), "IgnoreSerializableInterface") != null) { resolver.IgnoreSerializableInterface = true; } Newtonsoft.Json.Linq.JToken token; if (jObject.TryGetValue("discriminator", System.StringComparison.OrdinalIgnoreCase, out token)) { var discriminator = Newtonsoft.Json.Linq.Extensions.Value <string>(token); if (objectType.Name.Equals(discriminator) == false) { var exceptionType = System.Type.GetType("System." + discriminator, false); if (exceptionType != null) { objectType = exceptionType; } else { foreach (var pair in _searchedNamespaces) { exceptionType = pair.Value.GetType(pair.Key + "." + discriminator); if (exceptionType != null) { objectType = exceptionType; break; } } } } } var value = jObject.ToObject(objectType, newSerializer); foreach (var property in GetExceptionProperties(value.GetType())) { var jValue = jObject.GetValue(resolver.GetResolvedPropertyName(property.Value)); var propertyValue = (object)jValue?.ToObject(property.Key.PropertyType); if (property.Key.SetMethod != null) { property.Key.SetValue(value, propertyValue); } else { field = GetField(objectType, "m_" + property.Value.Substring(0, 1).ToLowerInvariant() + property.Value.Substring(1)); if (field != null) { field.SetValue(value, propertyValue); } } } SetExceptionFieldValue(jObject, "Message", value, "_message", resolver, newSerializer); SetExceptionFieldValue(jObject, "StackTrace", value, "_stackTraceString", resolver, newSerializer); SetExceptionFieldValue(jObject, "Source", value, "_source", resolver, newSerializer); SetExceptionFieldValue(jObject, "InnerException", value, "_innerException", resolver, serializer); return(value); }
public void NewtonsoftJsonSerialize() { var serializer = new Newtonsoft.Json.JsonSerializer() { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, }; var writer = new StringWriter(); serializer.Serialize(writer, ComplexMessage); Console.WriteLine(writer.ToString()); }
private void SetExceptionFieldValue(Newtonsoft.Json.Linq.JObject jObject, string propertyName, object value, string fieldName, Newtonsoft.Json.Serialization.IContractResolver resolver, Newtonsoft.Json.JsonSerializer serializer) { var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(System.Exception)).GetDeclaredField(fieldName); var jsonPropertyName = resolver is Newtonsoft.Json.Serialization.DefaultContractResolver ? ((Newtonsoft.Json.Serialization.DefaultContractResolver)resolver).GetResolvedPropertyName(propertyName) : propertyName; var property = System.Linq.Enumerable.FirstOrDefault(jObject.Properties(), p => System.String.Equals(p.Name, jsonPropertyName, System.StringComparison.OrdinalIgnoreCase)); if (property != null) { var fieldValue = property.Value.ToObject(field.FieldType, serializer); field.SetValue(value, fieldValue); } }
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { try { _isWriting = true; var jObject = Newtonsoft.Json.Linq.JObject.FromObject(value, serializer); jObject.AddFirst(new Newtonsoft.Json.Linq.JProperty(_discriminator, GetSubtypeDiscriminator(value.GetType()))); writer.WriteToken(jObject.CreateReader()); } finally { _isWriting = false; } }
private void CustomizedExceptionSerialization(StringBuilder builder, System.Exception exception) { try { Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer() { // disable serializable interface to allow e.g.: null value handling // this is needed to work properly with types implementing ISerializable interface ContractResolver = (_mode == WorkMode.Full) ? (new Newtonsoft.Json.Serialization.DefaultContractResolver() { IgnoreSerializableInterface = true }) : (new PartialSerializationContractResolver((_propertyNames != null) ? _propertyNames : _defaultPropertyNames)), Formatting = _mode == WorkMode.Slim ? Newtonsoft.Json.Formatting.None : Newtonsoft.Json.Formatting.Indented, NullValueHandling = _mode == WorkMode.Full ? Newtonsoft.Json.NullValueHandling.Include : Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, }; // partial serialization to JObject var jsonObject = Newtonsoft.Json.Linq.JObject.FromObject(exception, jsonSerializer); // appending Exception type property to serialized if (_includeClassName) { if (exception.InnerException == null) { // optimization for simple exception jsonObject.Add(_className, exception.GetType().ToString()); } else { System.Collections.Generic.Stack <Tuple <string, Newtonsoft.Json.Linq.JObject> > stack = new Stack <Tuple <string, Newtonsoft.Json.Linq.JObject> >(); Newtonsoft.Json.Linq.JObject j = jsonObject; for (System.Exception e = exception; ; j = (Newtonsoft.Json.Linq.JObject)j["InnerException"]) { stack.Push(new Tuple <string, Newtonsoft.Json.Linq.JObject>(e.GetType().ToString(), j)); e = e.InnerException; if (e == null) { break; } } foreach (var pair in stack) { pair.Item2.Add(_className, pair.Item1); } } } builder.Append(jsonObject.ToString(jsonSerializer.Formatting)); } catch (Exception ex) { NLog.Common.InternalLogger.Error(ex, "Exception serialization failed. Newtonsoft.Json error."); } }
private static string BuildTokenPostFromInitialSiteRequest(string HTML, string userName, string password, out string postUrl) { ////Get the PPSX value string PPSX = "PassportR"; //Get this random PPFT value string PPFT = HTML.Remove(0, HTML.IndexOf("PPFT")); PPFT = PPFT.Remove(0, PPFT.IndexOf("value") + 7); PPFT = PPFT.Substring(0, PPFT.IndexOf("\"")); string scriptBody = null; var scriptMatch = Regex.Match(HTML, "<script type=\"text/javascript\">var ServerData = {(.)*};</script>"); if (scriptMatch.Success) { scriptBody = scriptMatch.Value; } int firstBracket = scriptBody.IndexOf('{'); int lastBracket = scriptBody.LastIndexOf('}'); scriptBody = scriptBody.Substring(firstBracket, lastBracket - firstBracket + 1); var jsonSerializer = new Newtonsoft.Json.JsonSerializer(); dynamic serverData = jsonSerializer.Deserialize(new Newtonsoft.Json.JsonTextReader(new StringReader(scriptBody))); postUrl = serverData.urlPost; string requestToken = string.Format("login={0}&passwd={1}&PPSX={2}&LoginOptions=2&PPFT={3}", userName, password, PPSX, PPFT); return requestToken; }
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { var exception = value as System.Exception; if (exception != null) { var resolver = serializer.ContractResolver as Newtonsoft.Json.Serialization.DefaultContractResolver ?? _defaultContractResolver; var jObject = new Newtonsoft.Json.Linq.JObject(); jObject.Add(resolver.GetResolvedPropertyName("discriminator"), exception.GetType().Name); jObject.Add(resolver.GetResolvedPropertyName("Message"), exception.Message); jObject.Add(resolver.GetResolvedPropertyName("StackTrace"), _hideStackTrace ? "HIDDEN" : exception.StackTrace); jObject.Add(resolver.GetResolvedPropertyName("Source"), exception.Source); jObject.Add(resolver.GetResolvedPropertyName("InnerException"), exception.InnerException != null ? Newtonsoft.Json.Linq.JToken.FromObject(exception.InnerException, serializer) : null); foreach (var property in GetExceptionProperties(value.GetType())) { var propertyValue = property.Key.GetValue(exception); if (propertyValue != null) { jObject.AddFirst(new Newtonsoft.Json.Linq.JProperty(resolver.GetResolvedPropertyName(property.Value), Newtonsoft.Json.Linq.JToken.FromObject(propertyValue, serializer))); } } value = jObject; } serializer.Serialize(writer, value); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var jObject = serializer.Deserialize<Newtonsoft.Json.Linq.JObject>(reader); if (jObject == null) return null; var newSerializer = new Newtonsoft.Json.JsonSerializer(); newSerializer.ContractResolver = (Newtonsoft.Json.Serialization.IContractResolver)System.Activator.CreateInstance(serializer.ContractResolver.GetType()); GetField(typeof(Newtonsoft.Json.Serialization.DefaultContractResolver), "_sharedCache").SetValue(newSerializer.ContractResolver, false); dynamic resolver = newSerializer.ContractResolver; if (System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperty(newSerializer.ContractResolver.GetType(), "IgnoreSerializableAttribute") != null) resolver.IgnoreSerializableAttribute = true; if (System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperty(newSerializer.ContractResolver.GetType(), "IgnoreSerializableInterface") != null) resolver.IgnoreSerializableInterface = true; Newtonsoft.Json.Linq.JToken token; if (jObject.TryGetValue("discriminator", System.StringComparison.OrdinalIgnoreCase, out token)) { var discriminator = Newtonsoft.Json.Linq.Extensions.Value<string>(token); if (objectType.Name.Equals(discriminator) == false) { var exceptionType = System.Type.GetType("System." + discriminator, false); if (exceptionType != null) objectType = exceptionType; else { foreach (var pair in _searchedNamespaces) { exceptionType = pair.Value.GetType(pair.Key + "." + discriminator); if (exceptionType != null) { objectType = exceptionType; break; } } } } } var value = jObject.ToObject(objectType, newSerializer); foreach (var property in GetExceptionProperties(value.GetType())) { var jValue = jObject.GetValue(resolver.GetResolvedPropertyName(property.Value)); var propertyValue = (object)jValue?.ToObject(property.Key.PropertyType); if (property.Key.SetMethod != null) property.Key.SetValue(value, propertyValue); else { var field = GetField(objectType, "m_" + property.Value.Substring(0, 1).ToLowerInvariant() + property.Value.Substring(1)); if (field != null) field.SetValue(value, propertyValue); } } SetExceptionFieldValue(jObject, "Message", value, "_message", resolver, newSerializer); SetExceptionFieldValue(jObject, "StackTrace", value, "_stackTraceString", resolver, newSerializer); SetExceptionFieldValue(jObject, "Source", value, "_source", resolver, newSerializer); SetExceptionFieldValue(jObject, "InnerException", value, "_innerException", resolver, serializer); return value; }
public AnyUniqueAliasesUnion ReadJson(Newtonsoft.Json.JsonReader reader, AnyUniqueAliasesUnion _o, Newtonsoft.Json.JsonSerializer serializer) { if (_o == null) { return(null); } switch (_o.Type) { default: break; case AnyUniqueAliases.M: _o.Value = serializer.Deserialize <MyGame.Example.MonsterT>(reader); break; case AnyUniqueAliases.TS: _o.Value = serializer.Deserialize <MyGame.Example.TestSimpleTableWithEnumT>(reader); break; case AnyUniqueAliases.M2: _o.Value = serializer.Deserialize <MyGame.Example2.MonsterT>(reader); break; } return(_o); }
/// <summary> /// Default serializer with overload for allowing custom Json.NET settings /// </summary> public JsonSerializer(Newtonsoft.Json.JsonSerializer serializer) { ContentType = "application/json"; _serializer = serializer; }
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { var _olist = value as System.Collections.Generic.List <AnyUniqueAliasesUnion>; if (_olist != null) { writer.WriteStartArray(); foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } writer.WriteEndArray(); } else { this.WriteJson(writer, value as AnyUniqueAliasesUnion, serializer); } }
/// <summary> /// Creates a temporary verification file. /// </summary> /// <returns>The verification file.</returns> /// <param name="db">The database instance</param> /// <param name="stream">The stream to write to</param> public static void CreateVerificationFile(LocalDatabase db, System.IO.StreamWriter stream) { var s = new Newtonsoft.Json.JsonSerializer(); s.Serialize(stream, db.GetRemoteVolumes().Cast<IRemoteVolume>().ToArray()); }
public void WriteJson(Newtonsoft.Json.JsonWriter writer, AnyUniqueAliasesUnion _o, Newtonsoft.Json.JsonSerializer serializer) { if (_o == null) { return; } serializer.Serialize(writer, _o.Value); }
public PhotonJsonNetSerializer(Newtonsoft.Json.JsonSerializer serializer) { this.serializer = serializer; }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var _olist = existingValue as System.Collections.Generic.List <AnyUniqueAliasesUnion>; if (_olist != null) { for (var _j = 0; _j < _olist.Count; ++_j) { reader.Read(); _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); } reader.Read(); return(_olist); } else { return(this.ReadJson(reader, existingValue as AnyUniqueAliasesUnion, serializer)); } }
private void HandleNotification(object state) { try { string response = (string)state; Utility.WriteDebugInfo(response); if (String.IsNullOrEmpty(response)) return; // empty response int index = response.IndexOf("\r\n"); if (index < 1) return; // malformed response - missing \r\n string l = response.Substring(0, index); if (String.IsNullOrEmpty(l)) return; // malformed response - no length specifier int length = 0; bool ok = int.TryParse(l, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture.NumberFormat, out length); if (!ok) return; // malformed response - invalid length specifier int start = index + 1; // index plus one to account for \n int total = start + length; if (start >= response.Length) return; // missing notification data if (total > response.Length) return; // truncated notification data // ok - if we are here, we are good to go string json = response.Substring(start, length); /* DONT USE THIS - we cant control the JsonSerializer so we cant set the MissingMemberHandling property object obj = Newtonsoft.Json.JavaScriptConvert.DeserializeObject(json, typeof(NotificationReceivedEventArgs)); NotificationReceivedEventArgs args = (NotificationReceivedEventArgs)obj; * */ System.IO.StringReader sr = new System.IO.StringReader(json); using (sr) { Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer(); js.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; js.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; NotificationReceivedEventArgs args = (NotificationReceivedEventArgs) js.Deserialize(sr, typeof(NotificationReceivedEventArgs)); this.OnNotificationReceived(args); } } catch { // dont fail if the notification could not be handled properly } }
/// <inheritdoc/> public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { if (value == null) { writer.WriteNull(); } else { var bsonRegularExpression = (BsonRegularExpression)value; var adapter = writer as BsonWriterAdapter; if (adapter != null) { adapter.WriteRegularExpression(bsonRegularExpression); } else { var jsonDotNetBsonWriter = writer as Newtonsoft.Json.Bson.BsonWriter; if (jsonDotNetBsonWriter != null) { jsonDotNetBsonWriter.WriteRegex(bsonRegularExpression.Pattern, bsonRegularExpression.Options); } else { WriteExtendedJson(writer, bsonRegularExpression); } } } }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var jObject = serializer.Deserialize <Newtonsoft.Json.Linq.JObject>(reader); if (jObject == null) { return(null); } var discriminator = Newtonsoft.Json.Linq.Extensions.Value <string>(jObject.GetValue(_discriminator)); var subtype = GetObjectSubtype(objectType, discriminator); try { _isReading = true; return(serializer.Deserialize(jObject.CreateReader(), subtype)); } finally { _isReading = false; } }
} // End Sub WriteArray public virtual void SerializeDataTableAsAssociativeJsonArray(System.Data.Common.DbCommand cmd, System.IO.Stream output, bool pretty, System.Text.Encoding enc) { Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer(); using (System.IO.TextWriter sw = new System.IO.StreamWriter(output, enc)) { using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(sw)) { if (pretty) { jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; } // jsonWriter.WriteStartObject(); // jsonWriter.WritePropertyName("tables"); // jsonWriter.WriteStartArray(); using (System.Data.Common.DbConnection con = this.Connection) { cmd.Connection = con; if (con.State != System.Data.ConnectionState.Open) { con.Open(); } try { using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess | System.Data.CommandBehavior.CloseConnection )) { do { // jsonWriter.WriteStartObject(); // tbl = new Table(); //jsonWriter.WritePropertyName("columns"); //// WriteArray(jsonWriter, dr); //WriteAssociativeArray(jsonWriter, dr); //jsonWriter.WritePropertyName("rows"); jsonWriter.WriteStartArray(); if (dr.HasRows) { string[] columns = new string[dr.FieldCount]; for (int i = 0; i < dr.FieldCount; i++) { columns[i] = dr.GetName(i); } // Next i while (dr.Read()) { object[] thisRow = new object[dr.FieldCount]; // jsonWriter.WriteStartArray(); // object[] thisRow = new object[dr.FieldCount]; jsonWriter.WriteStartObject(); // tbl = new Table(); for (int i = 0; i < dr.FieldCount; ++i) { jsonWriter.WritePropertyName(columns[i]); object obj = dr.GetValue(i); if (obj == System.DBNull.Value) { obj = null; } jsonWriter.WriteValue(obj); } // Next i // jsonWriter.WriteEndArray(); // tbl.Rows.Add(thisRow); jsonWriter.WriteEndObject(); } // Whend } // End if (dr.HasRows) jsonWriter.WriteEndArray(); // jsonWriter.WriteEndObject(); // ser.Tables.Add(tbl); } while (dr.NextResult()); } // End using dr } catch (System.Exception ex) { System.Console.WriteLine(ex.Message); throw; } if (con.State != System.Data.ConnectionState.Closed) { con.Close(); } } // End using con // jsonWriter.WriteEndArray(); // jsonWriter.WriteEndObject(); jsonWriter.Flush(); } // End Using jsonWriter } // End Using sw } // End Sub SerializeDataTableAsAssociativeJsonArray