//инициализация 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 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(); } }
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 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; } }
static void Main(string[] args) { BinaryFormatter binarySerializer = new BinaryFormatter(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(List <Category>)); Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer(); using (var db = new DbNorthwind()) { // Eager loading List <Category> categories = db.Categories.Include(c => c.Products).ToList(); using (FileStream file = File.Create("CategoriesAndProducts.dat")) { binarySerializer.Serialize(file, categories); } using (FileStream file = File.Create("CategoriesAndProducts.xml")) { xmlSerializer.Serialize(file, categories); } using (StreamWriter file = File.CreateText(Combine(CurrentDirectory, "CategoriesAndProducts.json"))) { jsonSerializer.Serialize(file, categories); } } // Deserialed all formats to check using (FileStream file = File.Open("CategoriesAndProducts.xml", FileMode.Open)){ var cats = xmlSerializer.Deserialize(file) as List <Category>; foreach (var cat in cats) { WriteLine($"Category ID {cat.CategoryID}, category Name {cat.CategoryName}, {cat.Products.Count}"); } } using (FileStream file = File.Open("CategoriesAndProducts.dat", FileMode.Open)){ var cats = binarySerializer.Deserialize(file) as List <Category>; foreach (var cat in cats) { WriteLine($"Category ID {cat.CategoryID}, category Name {cat.CategoryName}, {cat.Products.Count}"); } } using (StreamReader file = File.OpenText("CategoriesAndProducts.json")) { var cats = jsonSerializer.Deserialize(file, typeof(List <Category>)) as List <Category>; foreach (var cat in cats) { WriteLine($"Category ID {cat.CategoryID}, category Name {cat.CategoryName}, {cat.Products.Count}"); } } }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type t, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { if (reader.TokenType == Newtonsoft.Json.JsonToken.Null) { return(null); } var value = serializer.Deserialize <string>(reader); if (long.TryParse(value, out long l)) { return(l); } throw new System.Exception("Cannot unmarshal type long"); }
/// <summary> /// Deserializes the given JSON http response content into the given object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="content"></param> /// <returns></returns> public async static Task <T> ReadJsonAsAsync <T>(this HttpContent content) { var json = await content.ReadAsStringAsync(); var serializer = new Newtonsoft.Json.JsonSerializer(); T result; using (var reader = new System.IO.StreamReader(await content.ReadAsStreamAsync())) { result = (T)serializer.Deserialize(reader, typeof(T)); } return(result); }
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); }
private async Task <TResponse> DeserialiseContentFromJson <TResponse>(HttpContent content) where TResponse : ResponseBase { using (var stream = await content.ReadAsStreamAsync().ConfigureAwait(false)) { using (var sr = new StreamReader(stream)) { using (var reader = new Newtonsoft.Json.JsonTextReader(sr)) { reader.ArrayPool = JsonArrayPool.Instance; return(_Serialiser.Deserialize <TResponse>(reader)); } } } }
public static async Task <T> ContentAsTypeStreamNewtonsoftAsync <T>(this HttpResponseMessage response) { using (var stream = await response.Content.ReadAsStreamAsync()) { using (var sr = new StreamReader(stream)) { using (var tr = new Newtonsoft.Json.JsonTextReader(sr)) { var serializer = new Newtonsoft.Json.JsonSerializer(); return(serializer.Deserialize <T>(tr)); } } } }
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(); } }
} // End Function GetParam public static T GetArgs <T>(System.Web.HttpContext context) { System.Type t = typeof(T); T args = System.Activator.CreateInstance <T>(); System.Reflection.FieldInfo[] fis = t.GetFields(); System.Reflection.PropertyInfo[] pis = t.GetProperties(); bool setNoValues = true; for (int i = 0; i < fis.Length; ++i) { string key = fis[i].Name; string value = GetParam(key, context); if (value != null) { fis[i].SetValue(args, FlexibleChangeType(value, fis[i].FieldType)); setNoValues = false; } // End if (value != null) } // Next i for (int i = 0; i < pis.Length; ++i) { string key = pis[i].Name; string value = GetParam(key, context); if (value != null) { pis[i].SetValue(args, FlexibleChangeType(value, pis[i].PropertyType), null); setNoValues = false; } // End if (value != null) } // Next i if (setNoValues) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream)) { using (Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(sr)) { args = (T)serializer.Deserialize(jsonTextReader, typeof(T)); } // End Using jsonTextReader } // End Using sr } // End if (setNoValues) return(args); } // End Function GetArgs
/// <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) { var configuration = new Configuration(); while (reader.Read() && reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName) { switch (reader.Value.ToString()) { case "partAttributes": reader.Read(); configuration.PartAttributes = serializer.Deserialize <AbstractAttributeDefinition[]>(reader); break; case "characteristicAttributes": reader.Read(); configuration.CharacteristicAttributes = serializer.Deserialize <AbstractAttributeDefinition[]>(reader); break; case "measurementAttributes": reader.Read(); configuration.MeasurementAttributes = serializer.Deserialize <AbstractAttributeDefinition[]>(reader); break; case "valueAttributes": reader.Read(); configuration.ValueAttributes = serializer.Deserialize <AbstractAttributeDefinition[]>(reader); break; case "catalogAttributes": reader.Read(); configuration.CatalogAttributes = serializer.Deserialize <AttributeDefinition[]>(reader); break; } } return(configuration); }
public DogApiDog[] Scrape() { string serviceUrl = "https://api.thedogapi.com/v1/images/search?size=med&mime_types=jpg&format=json&has_breeds=true&order=ASC&page=0&limit=100"; System.Net.WebRequest req = System.Net.WebRequest.Create(serviceUrl); req.Headers.Add("content-type", "application/json"); req.Headers.Add("x-api-key", _apiKey); System.Net.WebResponse response = req.GetResponse(); System.IO.Stream s = response.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(s); Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(sr); Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); return(serializer.Deserialize <DogApiDog[]>(jsonTextReader)); }
/// <summary> /// 解析JSON数组生成对象实体集合 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param> /// <returns>对象实体集合</returns> public static List <T> DeserializeJsonToList <T>(string json) where T : class { #if JSON_DOT_NET Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); StringReader sr = new StringReader(json); object o = serializer.Deserialize(new Newtonsoft.Json.JsonTextReader(sr), typeof(List <T>)); List <T> list = o as List <T>; return(list); #elif SIMPLE_JSON Log.Error("[TIPS]: The SimpleJson library cannot provide this method. Please use the JsonDotNet library."); #else Log.Error("[TIPS]: SimpleJson or JsonDotNet, Please add a macro definition SIMPLE_JSON or JSON_DOT_NET."); return(null); #endif }
public async Task <List <TodoDetailData> > GetById(int userId) { var hc = new HttpClient(); hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var res = await hc.GetAsync(common.GetURL() + "TodoDetailDatas/" + userId).ConfigureAwait(false);; var str = await res.Content.ReadAsStringAsync(); var js = new Newtonsoft.Json.JsonSerializer(); var jr = new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(str)); var item = js.Deserialize <List <TodoDetailData> >(jr); return(item); }
} // End Sub SerializeAndIgnoreSerializableInterface public static T Deserialize <T>(System.IO.Stream s) { T retValue = default(T); using (System.IO.StreamReader reader = new System.IO.StreamReader(s, System.Text.Encoding.UTF8)) { using (Newtonsoft.Json.JsonTextReader jsonReader = new Newtonsoft.Json.JsonTextReader(reader)) { Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer(); retValue = ser.Deserialize <T>(jsonReader); } // End Using jsonReader } // End Using reader return(retValue); } // End Function Deserialize
public override object DeserializeCore(Type type, byte[] value) { if (type.IsEnum) { var str = Encoding.UTF8.GetString(value); var v = Enum.Parse(type, str); return(v); } using (var ms = new MemoryStream(value)) using (var sr = new StreamReader(ms, new UTF8Encoding(false))) { return(serializer.Deserialize(sr, type)); } }
private T Deserialize <T>(Stream stream) { if (stream == null || !stream.CanRead) { return(default(T)); } using (var sr = new StreamReader(stream)) using (var jtr = new Newtonsoft.Json.JsonTextReader(sr)) { var js = new Newtonsoft.Json.JsonSerializer(); var value = js.Deserialize <T>(jtr); return(value); } }
public static AlermSettings Load(string path) { try { using (var reader = new StreamReader(path)) { var deserializer = new Newtonsoft.Json.JsonSerializer(); return((AlermSettings)deserializer.Deserialize(reader, typeof(AlermSettings))); } } catch (Exception) { return(new AlermSettings()); } }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns></returns> public static T DeserializeBson <T>(byte[] data) { try { using (var file = new System.IO.MemoryStream(data)) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); Newtonsoft.Json.Bson.BsonReader reader = new Newtonsoft.Json.Bson.BsonReader(file); return(serializer.Deserialize <T>(reader)); } } catch (Exception) { throw; } }
public static void SetupNewtonsoftJson( out Action <object, ChunkedMemoryStream> serialize, out Func <ChunkedMemoryStream, Type, object> deserialize) { var serializer = new Newtonsoft.Json.JsonSerializer(); serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple; serializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto; serialize = (obj, stream) => { var sw = new Newtonsoft.Json.JsonTextWriter(stream.GetWriter()); serializer.Serialize(sw, obj); sw.Flush(); }; deserialize = (stream, type) => serializer.Deserialize(new Newtonsoft.Json.JsonTextReader(stream.GetReader()), type); }
public static T Deserialize <T>(System.IO.Stream stream) { T objReturnValue = default(T); Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); using (System.IO.TextReader sr = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8)) { using (Newtonsoft.Json.JsonReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(sr)) { objReturnValue = serializer.Deserialize <T>(jsonTextReader); } } return(objReturnValue); }
private static void LoadConfig() { if (File.Exists(ConfigPath)) { using (var file = File.OpenText(ConfigPath)) { var serializer = new JsonSerializer(); _config = (Config)serializer.Deserialize(file, typeof(Config)); } } else { Console.WriteLine("No secrets.json found! I Have no idea what to do..."); Environment.Exit(1); } }
public static T Parse <T>(Stream stream, Newtonsoft.Json.JsonSerializerSettings settings = null) where T : class { try { var serializer = new Newtonsoft.Json.JsonSerializer(); if (settings != null) { serializer.ContractResolver = settings.ContractResolver; } using (var reader = new StreamReader(stream)) { return(serializer.Deserialize(reader, typeof(T)) as T); } } catch (Exception) { } return(default(T)); }
public static void Scrape() { string serviceUrl = "https://www.datakick.org/api/items"; //string serviceUrl = "http://www.ctabustracker.com/bustime/api/v2/getroutes?key=[APIKEY]&format=json"; System.Net.WebRequest req = System.Net.WebRequest.Create(serviceUrl); System.Net.WebResponse response = req.GetResponse(); System.IO.Stream s = response.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(s); Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(sr); Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); DataKickObject[] result = serializer.Deserialize <DataKickObject[]>(jsonTextReader); //CtaResponse result = serializer.Deserialize<CtaResponse>(jsonTextReader); //TODO: I've pulled data in -- I should save it somewhere so it's readily available when my app needs it! }
/// <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) { var catalogue = new Catalog(); if (reader.TokenType == Newtonsoft.Json.JsonToken.StartObject) { while (reader.Read() && reader.TokenType != Newtonsoft.Json.JsonToken.EndObject) { switch (reader.Value.ToString()) { case "name": catalogue.Name = reader.ReadAsString(); break; case "uuid": catalogue.Uuid = new Guid(reader.ReadAsString()); break; case "validAttributes": if (reader.Read() && reader.TokenType == Newtonsoft.Json.JsonToken.StartArray) { var atts = new List <ushort>(); while (reader.Read() && reader.TokenType != Newtonsoft.Json.JsonToken.EndArray) { atts.Add(Convert.ToUInt16(reader.Value)); } catalogue.ValidAttributes = atts.ToArray(); } break; case "catalogueEntries": if (reader.Read() && reader.TokenType == Newtonsoft.Json.JsonToken.StartArray) { if (reader.Read() && reader.TokenType == Newtonsoft.Json.JsonToken.StartObject) { var entries = new List <CatalogEntry>(); while (reader.TokenType != Newtonsoft.Json.JsonToken.EndArray) { entries.Add(serializer.Deserialize <CatalogEntry>(reader)); reader.Read(); } catalogue.CatalogEntries = entries.ToArray(); } } break; } } } return(catalogue); }
public static T JsonLoad <T>(System.IO.TextReader stream, bool includeNonPublic = false) { Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer(); Newtonsoft.Json.Serialization.DefaultContractResolver dcr = new Newtonsoft.Json.Serialization.DefaultContractResolver(); if (includeNonPublic) { #pragma warning disable CS0618 // Type or member is obsolete dcr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic; #pragma warning restore CS0618 // Type or member is obsolete ser.ConstructorHandling = Newtonsoft.Json.ConstructorHandling.AllowNonPublicDefaultConstructor; } ser.ContractResolver = dcr; ser.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto; ser.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; //ser.Error += On_JsonLoadError; return((T)ser.Deserialize(stream, typeof(T))); }
private static T DeserializeJsonFromStream <T>(Stream stream) { if (stream == null || stream.CanRead == false) { return(default(T)); } stream.Position = 0; using (StreamReader sr = new StreamReader(stream)) { using (Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(sr)) { Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer(); T result = js.Deserialize <T>(jtr); return(result); } } }
/// <summary> /// Carga el fichero de configuración. /// </summary> /// <param name="file"> /// <see cref="string" /> que contiene el nombre del fichero. /// </param> /// <returns> /// Devuelve un objeto <see cref="ConfigSettings" />. /// </returns> public static Settings Load(string file) { Settings settings = new Settings(); if (!System.IO.File.Exists(file)) { return(settings); } using (System.IO.StreamReader ini = System.IO.File.OpenText(file)) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); settings = (Settings)serializer.Deserialize(ini, typeof(Settings)); } return(settings); }
public static T Decode <T>(byte[] data) { try { using (var stream = new MemoryStream(data)) { using (var reader = new BsonDataReader(stream)) { var serializer = new Newtonsoft.Json.JsonSerializer(); var deserialised = serializer.Deserialize <T>(reader); return((T)deserialised); } } } catch (ArgumentOutOfRangeException ex) when(ex.ParamName == "type") { return(default);
private async Task <T> Deserialize <T>(HttpResponseMessage httpResponse) { var httpContent = httpResponse.Content; byte[] contentBytes = await httpContent.ReadAsByteArrayAsync(); var encodingResolver = new EncodingResolver(); string responseMediaType = httpContent.Headers.ContentType?.MediaType ?? this.DefaultMediaType; var encoding = encodingResolver.ResolveEncoding(responseMediaType, this.DefaultEncoding); var textReader = new StreamReader(new MemoryStream(contentBytes), encoding); var jsonTextReader = new Newtonsoft.Json.JsonTextReader(textReader); var serializer = new Newtonsoft.Json.JsonSerializer(); return(serializer.Deserialize <T>(jsonTextReader)); }
private static SerializedCulture GetSerializedCulture(string CultureName) { var Serialized = new Newtonsoft.Json.JsonSerializer(); using (var Stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Teva.Common.Cultures.cultures." + CultureName.ToLower() + ".json")) { if (Stream == null) { return(null); } using (var StreamReader = new System.IO.StreamReader(Stream, System.Text.Encoding.UTF32)) using (var JsonTextReader = new Newtonsoft.Json.JsonTextReader(StreamReader)) { return(Serialized.Deserialize <SerializedCulture>(JsonTextReader)); } } }
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 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); } } }
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(); } }
/// <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; }
private Item _LoadFromDisk(string fileId) { try { string journalFilePath = ""; Item item = null; try { journalFilePath = Settings.GetJournalFilePath(fileId + ".item", false); if (!FileExists(journalFilePath)) { return null; } DateTime lastWriteTime = GetFileLastWriteTime(journalFilePath); using ( System.IO.FileStream fileStream = OpenFile(journalFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { using (var streamReader = new System.IO.StreamReader(fileStream)) { using (Newtonsoft.Json.JsonReader jsonReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var jsonSerializer = new Newtonsoft.Json.JsonSerializer(); item = (Item)jsonSerializer.Deserialize(jsonReader, typeof (Item)); } } } if (item == null || item.Status != ItemStatus.Cached) { throw new Exception("Json parsing failed"); } _AddItem(item); } catch (Exception exception) { Log.Error(exception, false, false); try { DeleteFile(journalFilePath); } catch (Exception exception2) { Log.Error(exception2, false, false); } return null; } Item[] children = null; try { journalFilePath = Settings.GetJournalFilePath(fileId + ".children", false); if (!FileExists(journalFilePath)) { return null; } using ( System.IO.FileStream fileStream = OpenFile(journalFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { using (var streamReader = new System.IO.StreamReader(fileStream)) { using (Newtonsoft.Json.JsonReader jsonReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var jsonSerializer = new Newtonsoft.Json.JsonSerializer(); children = (Item[])jsonSerializer.Deserialize(jsonReader, typeof (Item[])); } } } if (children == null) { throw new Exception("Json parsing failed"); } foreach (Item child in children) { _AddItem(child); } } catch (Exception exception) { Log.Error(exception, false, false); try { DeleteFile(journalFilePath); } catch (Exception exception2) { Log.Error(exception2, false, false); } return null; } return item; } catch (Exception exception) { Log.Error(exception, false); return null; } }
// Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) using (var stream = new IsolatedStorageFileStream("data.txt", FileMode.OpenOrCreate, FileAccess.Read, store)) using (var reader = new StreamReader(stream)) { if (!reader.EndOfStream) { var serializer = new Newtonsoft.Json.JsonSerializer(); ViewModel = (MainViewModel)serializer.Deserialize(reader, typeof(MainViewModel)); } } // if the view model is not loaded, create a new one if (ViewModel == null) { ViewModel = new MainViewModel(); } RootFrame.DataContext = ViewModel; }
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 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 ); }
private void DeserializeJsonNetBenchInner() { Newtonsoft.Json.JsonSerializer ds = new Newtonsoft.Json.JsonSerializer(); TestObject t; Type ty = typeof(TestObject); for (int i = 0; i < JsonNetIterations; i++) { StringReader sr = new StringReader(JsonNetJson); t = (TestObject)ds.Deserialize(sr, ty); Escape(t.Name); } }
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; }
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 } }
private void DeserializeJsonNetBinaryBenchInner() { Newtonsoft.Json.JsonSerializer ds = new Newtonsoft.Json.JsonSerializer(); TestObject t; Type ty = typeof(TestObject); for (int i = 0; i < JsonNetIterations; i++) { BsonReader br = new BsonReader(new MemoryStream(JsonNetBinary)); t = (TestObject) ds.Deserialize(br, ty); Escape(t.Name); } }
public static List<QueryResult> callTrademeApi(String Searhword) { WebClient client = new WebClient(); String s = client.DownloadString(String.Format("https://api.trademe.co.nz/v1/Search/General.json?buy=All&{0}&photo_size=Gallery", Searhword)); var serializer = new Newtonsoft.Json.JsonSerializer(); var results = (SearchResults)serializer.Deserialize(new StringReader(s), typeof(SearchResults)); var queryResults = new List<QueryResult>(); foreach (Listing l in results.List) { var result = new QueryResult(); result.Title = l.Title; result.Price = l.PriceDisplay; result.HyperlinkUrl = string.Format("http://www.trademe.co.nz/{0}", l.ListingId); result.ImageUrl = l.PictureHref; queryResults.Add(result); } return queryResults; }