static void SendObject(object obj) { try { TcpClient client = new TcpClient("77.47.204.176", 85); NetworkStream stream = client.GetStream(); System.Runtime.Serialization.Json.DataContractJsonSerializer serializator = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); serializator.WriteObject(stream, obj); byte[] data = new byte[1024]; string responseData = String.Empty; int bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); Console.WriteLine("Received: {0}", responseData); stream.Close(); client.Close(); } catch (ArgumentNullException e) { Console.WriteLine("Argument null exception: {0}", e.ToString()); } catch (SocketException e) { Console.WriteLine("Socket exception: {0}", e.ToString()); } Console.WriteLine("End of send message..."); }
public virtual async Task<WeatherInfo> GetWeatherInfoAsync() { System.Runtime.Serialization.Json.DataContractJsonSerializer jsonsr = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(WeatherInfoBase)); // Command /get_dev_list /get_dev_list /get_dev_list //Parameters - - - //Response Body { list: [ { addr: “”, type: “”, pan: “”, mac: “”, visibility: 1, },...] } //array(object) //string string string string int //device id //device id device type device pan id MAC Address visibility WeatherInfoBase info = null; MyWebClient wc = new MyWebClient(); using (Stream stream = await wc.OpenReadTaskAsync(WeatherUriBase + "/env_sensor.get_dev_info")) { info = jsonsr.ReadObject(stream) as WeatherInfoBase; ; } info.info.Humidity *= 0.001; info.info.Temperature *= 0.1; info.info.PM25 *= 0.1; info.info.WindDirection *= 0.1; info.info.WindSpeed *= 0.1; info.info.WaterLevel *= 0.1; info.info.RainFall *= 0.1; return info.info; }
// GET: Api/Post/Add3 public JsonResult Add3() { PostModel model = new PostModel(); model.PDate = DateTime.Now; string fileName = Server.MapPath("~/App_Data/test3.json"); model.PText = fileName; System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(PostModel)); System.IO.MemoryStream stream1 = new System.IO.MemoryStream(); ser.WriteObject(stream1, model); using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { byte[] jsonArray = stream1.ToArray(); using (System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress)) { gz.Write(jsonArray, 0, jsonArray.Length); } } return Json(model, JsonRequestBehavior.AllowGet); }
/// <summary> /// Bing requires their Adm access token for translation /// </summary> /// <returns></returns> private AdmAccessToken RequestAdmAccessToken() { // Create the request for Adm access token System.Net.WebRequest webRequest = System.Net.WebRequest.Create(_translatorAccessURI); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; // Create the contents for request var requestDetails = string.Format(_requestDetails, _clientID, _clientSecret); byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestDetails); webRequest.ContentLength = bytes.Length; // Write the contents into request stream using (System.IO.Stream outputStream = webRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } // Fetch the response System.Net.WebResponse webResponse = webRequest.GetResponse(); // Serialize and return the access token var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken)); return (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); }
public static Manager Read(Stream stream, Func<ObjectElement,Manager> createManager) { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer( typeof(CommonLibs.ExceptionManager.SerializerHelper.SerializableNode[]) ); var nodes = (SerializerHelper.SerializableNode[])serializer.ReadObject( stream ); var root = SerializerHelper.RecreateObjectTree( nodes ); return createManager( root ); }
private void GetResponseCallback(IAsyncResult ar) { // STEP 3: Process the response callback to get the token // we'll then use that token to call the translator service // Pull the request out of the IAsynch result var request = (System.Net.HttpWebRequest)ar.AsyncState; // The request now has the response details in it (because we've called back having gotten the response var response = (System.Net.HttpWebResponse)request.EndGetResponse(ar); // Using JSON we'll pull the response details out, and load it into an AdmAccess token class (defined earlier in this module) // IMPORTANT (and vague) -- despite the name, in Windows Phone, this is in the System.ServiceModel.Web library, // and not the System.Runtime.Serialization one -- so you will need to have a reference to System.ServiceModel.Web try { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken)); var token = (AdmAccessToken)serializer.ReadObject(response.GetResponseStream()); var uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Net.WebUtility.UrlEncode(_textToTranslate) + "&from=en&to=" + _targetLanguageCode; var translationWebRequest = System.Net.HttpWebRequest.Create(uri); // The authorization header needs to be "Bearer" + " " + the access token var headerValue = "Bearer " + token.access_token; translationWebRequest.Headers["Authorization"] = headerValue; // And now we call the service. When the translation is complete, we'll get the callback IAsyncResult writeRequestStreamCallback = (IAsyncResult)translationWebRequest.BeginGetResponse(new AsyncCallback(TranslationReady), translationWebRequest); } catch (Exception ex) { // Do nothing } }
private void SaveWebPost(string fileName, PostModel model) { WebPostModel wPost = new WebPostModel() { PTitle = model.PTitle, PText = model.PText, PLink = model.PLink, PImage = model.PImage, PDate = model.PDate.ToString("yyyy-MM-ddTHH:mm:ss"), PPrice = model.PPrice }; System.IO.MemoryStream msPost = new System.IO.MemoryStream(); System.Runtime.Serialization.Json.DataContractJsonSerializer dcJsonPost = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(WebPostModel)); dcJsonPost.WriteObject(msPost, wPost); using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { byte[] jsonArray = msPost.ToArray(); using (System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress)) { gz.Write(jsonArray, 0, jsonArray.Length); } } }
public static void Main(string[] args) { var p = new CgProgram(args); try { p.StartConsole(); if (p.PrintHelp()) return; p.ParseProgramArgs(); var cgType = Etc.GetCgOfType(p.Assembly, p.TypeName, false, p.ResolveDependencies); var dcs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof (CgType)); using (var std = Console.OpenStandardOutput()) { dcs.WriteObject(std, cgType); std.Flush(); std.Close(); } } catch (Exception ex) { p.PrintToConsole(ex); } Thread.Sleep(NfConfig.ThreadSleepTime);//slight pause }
public async Task<List<TrainService>> GetDepartures(ushort numberOfresults, string startingStation, string destinationStation = null) { string jsondata = "[{\"Destination\":\"London Waterloo\",\"ExpectedDepature\":\"On time\",\"ScheduledDeparture\":\"05:40\",\"ServiceID\":\"4Y4RiQh11azN2cNQbqXRMg==\"},{\"Destination\":\"London Waterloo\",\"ExpectedDepature\":\"On time\",\"ScheduledDeparture\":\"06:11\",\"ServiceID\":\"oLzkuSqsNqD3EXcBjlDnoA==\"},{\"Destination\":\"London Waterloo\",\"ExpectedDepature\":\"On time\",\"ScheduledDeparture\":\"06:34\",\"ServiceID\":\"KI1NhkIjHQTHu0EO\\/jHwnA==\"},{\"Destination\":\"London Waterloo\",\"ExpectedDepature\":\"On time\",\"ScheduledDeparture\":\"06:50\",\"ServiceID\":\"aU4o7Ay61mJk2bFgSTT2GQ==\"},{\"Destination\":\"London Waterloo\",\"ExpectedDepature\":\"07:50\",\"ScheduledDeparture\":\"07:00\",\"ServiceID\":\"R1+GaoylsCDD+zt5\\/9IIgg==\"},{\"Destination\":\"London Waterloo\",\"ExpectedDepature\":\"On time\",\"ScheduledDeparture\":\"07:11\",\"ServiceID\":\"Gl2YbopD\\/bQh+vZoHmXHFw==\"}]"; var deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<TrainService>)); var bytes = Encoding.Unicode.GetBytes(jsondata); return deserializer.ReadObject(new MemoryStream(bytes)) as List<TrainService>; }
public bool Submit() { WebClient wc = new WebClient(); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_endpoint); request.Method = "POST"; request.ContentType = "application/json;charset=utf-8"; request.MediaType = "application/json"; byte[] bytes = UTF8Encoding.UTF8.GetBytes(_request.Serialize()); request.ContentLength = bytes.Length; request.Headers.Add(HttpRequestHeader.Authorization, _authHeader); request.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback( delegate { return true; } ); try { using (System.IO.Stream strm = request.GetRequestStream()) { strm.Write(bytes, 0, bytes.Length); } HttpWebResponse rsp = (HttpWebResponse)request.GetResponse(); using (System.IO.Stream rdr = rsp.GetResponseStream()) { using (System.IO.StreamReader strmRdr = new System.IO.StreamReader(rdr)) { System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Processors.BBCS.REST.Transactional.Response)); Response resp = (Response)ser.ReadObject(strmRdr.BaseStream); } } } catch (WebException e) { using (WebResponse response = e.Response) { HttpWebResponse httpResponse = (HttpWebResponse)response; Console.WriteLine("Error code: {0}", httpResponse.StatusCode); using (System.IO.Stream data = response.GetResponseStream()) using (var reader = new System.IO.StreamReader(data)) { throw new Exception(reader.ReadToEnd()); } } } return true; }
public override ICloudCredentials GetCredentialsForRule(Rule rule, string arn) { System.Runtime.Serialization.Json.DataContractJsonSerializer jss = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(FnProjectFunction)); System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(rule.LambdaProperties)); FnProjectFunction func = (FnProjectFunction)jss.ReadObject(ms); return new FnProjectCredentials() { FuncObject = func, Cloud = this }; }
private static T DeSerialize(string json) { using (Stream stream = new MemoryStream()) { byte[] data = System.Text.Encoding.UTF8.GetBytes(json); stream.Write(data, 0, data.Length); stream.Position = 0; System.Runtime.Serialization.Json.DataContractJsonSerializer seria = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); return((T)seria.ReadObject(stream)); } }
private static string Serialize(T obj) { using (MemoryStream memorystream = new MemoryStream()) using (StreamReader reader = new StreamReader(memorystream, Encoding.UTF8)) { System.Runtime.Serialization.Json.DataContractJsonSerializer seria = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); seria.WriteObject(memorystream, obj); memorystream.Position = 0; return(reader.ReadToEnd()); } }
public Task InitializeAsync(string file) { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Dictionary <String, String>)); var assembly = System.Reflection.Assembly.GetEntryAssembly(); using (var stream = assembly.GetManifestResourceStream(file)) _values = serializer.ReadObject(stream) as Dictionary <String, String>; return(Task.FromResult <Object>(null)); }
private static string ComposeSettingsString(List <string> words) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <string>)); using (MemoryStream memstream = new MemoryStream()) { ser.WriteObject(memstream, words); memstream.Position = 0; return((new StreamReader(memstream)).ReadToEnd()); } }
public static string ToJSON(object obj) { using (var ms = new System.IO.MemoryStream()) { var dcs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); dcs.WriteObject(ms, obj); ms.Position = 0; var sr = new System.IO.StreamReader(ms); return(sr.ReadToEnd()); } }
/* * Taken from: http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx * * Example: * /// Our Person object to Serialize/Deserialize to JSON * [DataContract] * public class Person * { * public Person() { } * public Person(string firstname, string lastname) * { * this.FirstName = firstname; * this.LastName = lastname; * } * * [DataMember] * public string FirstName { get; set; } * * [DataMember] * public string LastName { get; set; } * } */ public static string Serialize <T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, obj); string retVal = Encoding.Default.GetString(ms.ToArray()); ms.Dispose(); return(retVal); }
public void Export(string assmName, string filename) { var model = this.Get(assmName); var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Models.PluginAssembly)); using (var file = new System.IO.FileStream(filename, System.IO.FileMode.Create)) { ser.WriteObject(file, model); } }
public string toJson() { System.Runtime.Serialization.Json.DataContractJsonSerializer js = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType()); MemoryStream ms = new MemoryStream(); js.WriteObject(ms, this); ms.Position = 0; StreamReader sr = new StreamReader(ms); return(sr.ReadToEnd()); }
public static string DumpObject(object obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, obj); string midstep = Encoding.Default.GetString(ms.ToArray()); return(FormatJson(midstep)); }
public static T Deserialize <T>(string json) { T obj = Activator.CreateInstance <T>(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); obj = (T)serializer.ReadObject(ms); ms.Close(); ms.Dispose(); return(obj); }
/// <summary> /// JSON格式字符转换为T类型的对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonStr"></param> /// <returns></returns> public static T ParseFormByJson<T>(string jsonStr) { T obj = Activator.CreateInstance<T>(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } }
/// <summary> /// Serialize an object graph to a stream /// </summary> /// <param name="stream">Stream to serialize into</param> /// <param name="o">Object graph of type T</param> public static void Serialize(Stream stream, object o) { #if IOS var js = new Newtonsoft.Json.JsonSerializer(); StreamWriter writer = new StreamWriter(stream); js.Serialize <T>(writer, o); #else var dc = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); dc.WriteObject(stream, o); #endif }
/** * Method is a debugging tool * * @param appointmentList */ private void debugPrint(Dictionary <int, List <TimeRange> > appointmentList) { Console.WriteLine("----------------------------------"); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(appointmentList.GetType()); System.IO.MemoryStream ms = new System.IO.MemoryStream(); serializer.WriteObject(ms, appointmentList); string json = Encoding.Default.GetString(ms.ToArray()); Console.WriteLine(json); Console.WriteLine("----------------------------------"); }
private static byte[] Serialize(Operacao operacao) { using (var ms = new System.IO.MemoryStream()) { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Operacao)); serializer.WriteObject(ms, operacao); byte[] json = ms.ToArray(); ms.Close(); return(json); } }
public CorrdinatorInfo GetDeviceInfo() { MyWebClient wc = new MyWebClient(); System.Runtime.Serialization.Json.DataContractJsonSerializer jsonsr = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(CorrdinatorInfo)); Stream stream; CorrdinatorInfo retInfo = jsonsr.ReadObject(stream = wc.OpenRead(UriBase + "/info")) as CorrdinatorInfo; stream.Close(); stream.Dispose(); return retInfo; }
public string ToJson() { var jsonSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType()); var ms = new MemoryStream(); jsonSerializer.WriteObject(ms, this); var rdr = new StreamReader(ms); ms.Position = 0; return(rdr.ReadToEnd()); }
/// <summary> /// Function to deserialize JSON string using DataContractJsonSerializer /// </summary> /// <typeparam name="RemoteContextType">RemoteContextType Generic Type</typeparam> /// <param name="jsonString">string jsonString</param> /// <returns>Generic RemoteContextType object</returns> public static RemoteContextType DeserializeJsonString <RemoteContextType>(string jsonString) { //create an instance of generic type object RemoteContextType obj = Activator.CreateInstance <RemoteContextType>(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); obj = (RemoteContextType)serializer.ReadObject(ms); ms.Close(); return(obj); }
/// <summary> /// Serializes an object to a Json string /// </summary> /// <typeparam name="TType">The type of object to serialize</typeparam> /// <param name="this">The object to serialize to Json</param> /// <returns>A Json formatted string representation of the specified object</returns> //[System.Diagnostics.DebuggerStepThrough] public static string AsJson <TType>(this object @this) { var s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(TType)); //var s = new DataContractJsonSerializer(typeof(TType), new DataContractJsonSerializerSettings() { EmitTypeInformation = EmitTypeInformation.Always, UseSimpleDictionaryFormat = false}); using (var stream = new System.IO.MemoryStream()) { s.WriteObject(stream, @this); return(stream.ToArray().AsString()); } }
private async void Window_Loaded(object sender, RoutedEventArgs e) { HttpClient httpClient = new HttpClient(); string result = await httpClient.GetStringAsync("https://api.ip.sb/geoip"); this.txt.Text = result; System.Runtime.Serialization.Json.DataContractJsonSerializer json = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(GetIpModel)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result)); GetIpModel model = json.ReadObject(ms) as GetIpModel; this.DataContext = model; }
/// <summary> /// Deserializes the object from JSON string format. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json">The json.</param> /// <returns></returns> public static T JsonDeserialize <T>(string json) { T obj = default(T); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); obj = (T)serializer.ReadObject(ms); } return(obj); }
private string ConvertToJson <T>(T result) { var json = ""; using (var stream = new System.IO.MemoryStream()) { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); serializer.WriteObject(stream, result); json = System.Text.Encoding.UTF8.GetString(stream.ToArray()); } return(json); }
static void Main(string[] args) { //Http request System.Net.WebClient _httpRequest = new System.Net.WebClient(); //string resultFromService=_httpRequest.DownloadString("http://localhost:8007/restservice/servertime"); // Console.WriteLine(resultFromService); //post Method var _patient = new DataModelsLib.PatientInfo { MRN = "MRN009", Name = "Jacks", ContactNumber = "12345", Address = new DataModelsLib.Address { City = "Blr", PinCode = "56007", State = "Ka", Street = "abc" } }; System.Net.HttpWebRequest _httpPostReq = System.Net.WebRequest.CreateHttp("http://localhost:8008/pic/hmgmt/patients/add"); _httpPostReq.Method = "POST"; _httpPostReq.ContentType = "application/json"; System.Runtime.Serialization.Json.DataContractJsonSerializer patientDataJsonSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(DataModelsLib.PatientInfo)); patientDataJsonSerializer.WriteObject(_httpPostReq.GetRequestStream(), _patient); System.Net.HttpWebResponse response = _httpPostReq.GetResponse() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) { Console.WriteLine("New Patient Added successfully"); } //Get System.Net.HttpWebRequest _httpReq = System.Net.WebRequest.CreateHttp("http://localhost:8008/pic/hmgmt/patients"); _httpReq.Method = "GET"; response = _httpReq.GetResponse() as System.Net.HttpWebResponse; if (response.StatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("Communication Successful"); Console.WriteLine(response.ContentType); Console.WriteLine(response.ContentLength); System.Runtime.Serialization.Json.DataContractJsonSerializer _jsonSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(DataModelsLib.PatientInfo[])); DataModelsLib.PatientInfo[] patients = _jsonSerializer.ReadObject(response.GetResponseStream()) as DataModelsLib.PatientInfo[]; foreach (var patient in patients) { Console.WriteLine($"{patient.MRN} nad {patient.Name}"); } } }
public static T?Deserialize <T>(string json) where T : class { var obj = Activator.CreateInstance <T>(); var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)); var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); obj = serializer.ReadObject(ms) as T; ms.Close(); return(obj); }
public static void Save() { if (!Settings.Current.Uninstalled) { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Settings)); var strSaveFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\CleanShot"; Directory.CreateDirectory(strSaveFolder); var fs = new FileStream(strSaveFolder + @"\Settings.json", FileMode.Create); serializer.WriteObject(fs, Settings.Current); fs.Close(); } }
/// <summary> /// Deserializes an encoded byte array of Json to an object /// </summary> /// <typeparam name="TType">The type of object to deserialize</typeparam> /// <param name="this">The byte array containing encoded Json</param> /// <returns>A new instance of TType deserialized from the specified Json encoded byte array</returns> public static TType FromJson <TType>(this byte[] @this) { var result = default(TType); using (var stream = new System.IO.MemoryStream()) { stream.Write(@this, 0, @this.Length); var s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(TType)); result = (TType)s.ReadObject(stream); } return(result); }
/// <summary> /// Deserializes an object from a UTF-8 encoded JSON string. /// </summary> /// <typeparam name="T">type of object to deserialize as</typeparam> /// <param name="json">UTF-8 encoded JSON string</param> /// <returns>deserialized object</returns> public static T DeserializeJSON <T>(string json) { MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); T obj = (T)serializer.ReadObject(ms); //Remember to Close MemoryStream ms.Close(); ms.Dispose(); return(obj); }
private void Send(BaseReturn ret,HttpContext context) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(BaseReturn)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { serializer.WriteObject(ms, ret); byte[] b = ms.ToArray(); context.Response.OutputStream.Write(b, 0, b.Length); context.Response.Flush(); } }
///// <summary> ///// Serializes the <paramref name="inputObject"/> instance using the specified <paramref name="output"/> stream. ///// </summary> ///// <typeparam name="T">The types of object to serialize</typeparam> ///// <param name="inputObject">The object to serialize</param> ///// <param name="output">The stream to write the serialization to.</param> ///// <param name="knownTypes">Known types used during serialization.</param> //public static void Serialize<T>(T inputObject, System.IO.Stream output, IEnumerable<Type> knownTypes = null) // where T : class //{ // List<Type> allTypes = new List<Type>(); // if (knownTypes != null) // allTypes.AddRange(knownTypes); // var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T), allTypes); // serializer.WriteObject(output, inputObject); //} ///// <summary> ///// Deserializes a new instance of <typeparamref name="T"/> using the specified <paramref name="input"/> stream. ///// </summary> ///// <typeparam name="T">The type of object to deserialize.</typeparam> ///// <param name="input">The input stream to read.</param> ///// <param name="knownTypes">Known types used during deserialization.</param> ///// <returns>A new object instance.</returns> //public static T Deserialize<T>(System.IO.Stream input, IEnumerable<Type> knownTypes = null) // where T : class //{ // List<Type> allTypes = new List<Type>(); // if (knownTypes != null) // allTypes.AddRange(knownTypes); // var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T), allTypes); // return serializer.ReadObject(input) as T; //} /// <summary> /// Serializes the <paramref name="instance"/> instance to the specified file. /// </summary> /// <typeparam name="T">Type of object to serialize</typeparam> /// <param name="instance">The object to serialize.</param> /// <param name="file">The file to save the object to.</param> /// <param name="knownTypes">Optional list of known types for serialization.</param> public static void Save <T>(T instance, string file, IEnumerable <Type> knownTypes = null) { if (System.IO.File.Exists(file)) { System.IO.File.Delete(file); } var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T), knownTypes, int.MaxValue, false, new SerializerSurrogate(), false); using (var stream = System.IO.File.OpenWrite(file)) serializer.WriteObject(stream, instance); }
/// <summary> /// Десериализира JSON /// </summary> public static object JsonDeserialize(string jsonString, Type type) { object jsonObject = null; using (var jsonMemoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { var jsonSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(type); jsonObject = jsonSerializer.ReadObject(jsonMemoryStream); } return(jsonObject); }
/// <summary>Deserializes the JSON string as a specified object</summary> /// <typeparam name="T">Specified type of target object</typeparam> /// <param name="jsonString">JSON string source</param> /// <returns>Object of specied type</returns> private static T Deserialize <T>(string jsonString) { using (System.IO.MemoryStream _Stream = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { try { var _Serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); return((T)_Serializer.ReadObject(_Stream)); } catch (Exception) { throw; } } }
public static string Serialize <T>(T obj) { using (var mstream = new MemoryStream()) { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); serializer.WriteObject(mstream, obj); mstream.Position = 0; using (var sr = new StreamReader(mstream)) { return(sr.ReadToEnd()); } } }
private void doWork() { while (true) { try { List<Channel> channels; lock (_in_queue) { while (_in_queue.Count == 0 && !doExit) Monitor.Wait(_in_queue); if (doExit) break; channels = _in_queue.Dequeue(); } Regex regex; lock (_sw) { regex = new Regex(_sw.val, RegexOptions.IgnoreCase); } List<Article> res = new List<Article>(); foreach (Channel channel in channels) foreach (Article article in channel.articles) { if (regex.IsMatch(article.title) || regex.IsMatch(article.description)) res.Add(article); } var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<Article>)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, res); string res_str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); HttpWebRequest request = WebRequest.Create("http://localhost:49714/WebService.svc/enqueue_mailer") as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = Encoding.UTF8.GetByteCount(res_str); StreamWriter sw = new StreamWriter(request.GetRequestStream()); sw.Write(res_str); sw.Close(); request.GetResponse(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } }
public void SaveStore() { lock (this) { using (var filesystem = IsolatedStorageFile.GetUserStoreForApplication()) { using (var fs = new IsolatedStorageFileStream(this.storeName, FileMode.Create, filesystem)) { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(TaskCollection)); serializer.WriteObject(fs, this.AllTasks); } } } }
public Stream AdvancedSearchJSONP(string mode, string terms, string key, string callback) { List<vwar.service.host.SearchResult> md = AdvancedSearch(mode, terms, key); MemoryStream stream1 = new MemoryStream(); System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<vwar.service.host.SearchResult>)); ser.WriteObject(stream1, md); stream1.Seek(0, SeekOrigin.Begin); System.IO.StreamReader sr = new StreamReader(stream1); string data = sr.ReadToEnd(); data = callback + "(" + data + ");"; byte[] a = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(data); WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; return new MemoryStream(a); }
private const string STORAGE_ID = "H2O"; // H2O #endregion Fields #region Methods public static void WriteBriefs() { using (var service = new ExecutionBrokerService.ExecutionBrokerServiceClient()) { var briefs = service.GetBriefTaskList(); var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(briefs.GetType()); var memStream = new MemoryStream(); serializer.WriteObject(memStream, (object) briefs); string json = Encoding.UTF8.GetString(memStream.ToArray()); memStream.Close(); Console.WriteLine(); Console.WriteLine(json); Console.WriteLine(); } }
public void setParams(string emails, string filter_regex) { var emails_arr = new string[0]; try { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string[])); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(emails)); emails_arr = (string[])ser.ReadObject(ms); } catch (Exception e) { Console.WriteLine(e.Message); } QueueKeeper.Instance.sw.val = filter_regex; QueueKeeper.Instance.emails = emails_arr; }
public static APODData GetAPOD() { var url = "https://api.nasa.gov/planetary/apod?api_key=QFm89VBBPK0iiZGOPdLeFhsXQd21PJC06zIGjTgm"; var syncClient = new WebClient(); var content = syncClient.DownloadString(url); var apodData = new APODData(); // Create the Json serializer and parse the response System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(APODData)); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content))) { apodData = (APODData)serializer.ReadObject(ms); } return (APODData)apodData; }
static void Main() { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Load our program settings var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ProgramSettings)); using (var fileObject = System.IO.File.OpenRead("Settings.json")) Settings.Config = serializer.ReadObject(fileObject) as ProgramSettings; // Setup the engine and creat the main window. SadConsole.Engine.Initialize(Settings.Config.ProgramFontFile, Settings.Config.WindowWidth, Settings.Config.WindowHeight); // Hook the start event so we can add consoles to the system. SadConsole.Engine.EngineStart += Engine_EngineStart; // Start the game. SadConsole.Engine.Run(); }
public static string Serialize(object obj) { if (obj == null) return null; var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); using (var stream = new MemoryStream()) { serializer.WriteObject(stream, obj); stream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(stream, Encoding.UTF8)) { return reader.ReadToEnd(); } } }
private void button1_Click(object sender, EventArgs e) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string[])); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, emails.ToArray()); string email_str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); WebRequest paramsWebRequest = WebRequest.Create("http://localhost:49714/WebService.svc/set_params?emails=" + Uri.EscapeDataString(email_str) + "&filter_regex=" + Uri.EscapeDataString(regexTextBox.Text)); paramsWebRequest.GetResponse(); foreach (String channel_url in URLlistBox.Items) { WebRequest urlWebRequest = WebRequest.Create("http://localhost:49714/WebService.svc/enqueue_url?url=" + Uri.EscapeDataString(channel_url)); urlWebRequest.GetResponse(); } }
public virtual WeatherInfo GetWeatherInfo() { MyWebClient wc = new MyWebClient(); System.Runtime.Serialization.Json.DataContractJsonSerializer jsonsr = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(WeatherInfoBase)); Stream stream; WeatherInfoBase retInfo = jsonsr.ReadObject(stream = wc.OpenRead(WeatherUriBase + "/env_sensor.get_dev_info")) as WeatherInfoBase; stream.Close(); stream.Dispose(); retInfo.info.Humidity *= 0.001; retInfo.info.Temperature *= 0.1; retInfo.info.PM25 *= 0.1; retInfo.info.WindDirection *= 0.1; retInfo.info.WindSpeed *= 0.1; retInfo.info.WaterLevel *= 0.1; retInfo.info.RainFall *= 0.1; return retInfo.info; }
public static object Deserialize(string json, Type objType) { Require.NotNull(objType, "objType"); if (String.IsNullOrEmpty(json)) return null; var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(objType); using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { writer.Write(json); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); return serializer.ReadObject(stream); } }
public static GeneralPurpose.Request GetBulkCreateRequest(Guid jobId, string tag, int recipientCount) { GeneralPurpose.Request r; Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); using (System.IO.StreamReader rdr = new System.IO.StreamReader(assembly.GetManifestResourceStream("DataContext.BBCS.GeneralPurpose.Resources.BulkCreateRequest.json"))) { System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(GeneralPurpose.Request)); r = (GeneralPurpose.Request)ser.ReadObject(rdr.BaseStream); } r.JobId = jobId.ToString(); if (string.IsNullOrWhiteSpace(r.JobId)) { r.JobId = Guid.NewGuid().ToString(); } if (string.IsNullOrEmpty(r.EmailContentHTML)) { using (System.IO.StreamReader strm = new System.IO.StreamReader(assembly.GetManifestResourceStream("DataContext.BBCS.GeneralPurpose.Resources.Content.html"))) { r.EmailContentHTML = strm.ReadToEnd(); } } if (string.IsNullOrWhiteSpace(r.CompressedMergeData) && !RequestFactory.GenerateMergeData) { using (System.IO.StreamReader strm = new System.IO.StreamReader(assembly.GetManifestResourceStream("DataContext.BBCS.GeneralPurpose.Resources.10.mergedata.xml"))) { string mergeData = strm.ReadToEnd(); r.CompressedMergeData = r.CompressMergeData(mergeData); } } else if (string.IsNullOrWhiteSpace(r.CompressedMergeData)) { r.CompressedMergeData = r.CompressMergeData(RequestFactory.AddMergeData(tag, recipientCount)); } return r; }
private void doWork() { while (true) { try { string url = ""; lock (_in_queue) { while (_in_queue.Count == 0 && !doExit) Monitor.Wait(_in_queue); if (doExit) break; url = _in_queue.Dequeue(); } List<Channel> res = RssFetcher.getFeedFromURL(url); var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<Channel>)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, res); string res_str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); HttpWebRequest request = WebRequest.Create("http://localhost:49714/WebService.svc/enqueue_filter") as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = Encoding.UTF8.GetByteCount(res_str); StreamWriter sw = new StreamWriter(request.GetRequestStream()); sw.Write(res_str); sw.Close(); request.GetResponse(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } }
public void enqueue_mailer(Stream input) { StreamReader reader = new StreamReader(input); string articles = reader.ReadToEnd(); var articles_arr = new List<Article>(); try { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<Article>)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(articles)); articles_arr = (List<Article>)ser.ReadObject(ms); } catch (Exception e) { Console.WriteLine(e.Message); } lock (QueueKeeper.Instance.send_queue) { QueueKeeper.Instance.send_queue.Enqueue(articles_arr); Monitor.Pulse(QueueKeeper.Instance.send_queue); } }
private string GetAccessToken() { String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(_clientId), HttpUtility.UrlEncode(_secret)); System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails); webRequest.ContentLength = bytes.Length; using (System.IO.Stream outputStream = webRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } System.Net.WebResponse webResponse = webRequest.GetResponse(); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken)); AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); return token.access_token; }
/** * example from * http://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx * */ public void testDataMemberSimple() { Person p = new Person(); p.name = "John"; p.age = 42; p.title = "Mr"; MemoryStream stream1 = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person)); ser.WriteObject(stream1, p); StreamReader sr = new StreamReader(stream1); stream1.Position=0; string strBuiltInJson = sr.ReadToEnd(); //Console.WriteLine(sr.ReadToEnd()); Console.WriteLine("inbuilt json=" + strBuiltInJson); Object2Json o2j = new Object2Json(); o2j.NodeExpander = new DataContractFieldNodeExpander(); string strJson = o2j.toJson(p); System.Console.WriteLine("json:" + strJson); // analyze with JsonExplorer JSONExplorerImpl jsonExplorer = new JSONExplorerImpl(); TestListener inbuiltListener = new TestListener(); TestListener listener = new TestListener(); jsonExplorer.explore(strBuiltInJson, inbuiltListener); jsonExplorer.explore(strJson, listener); Assert.AreEqual(inbuiltListener.leaves.Keys.Count, listener.leaves.Keys.Count, "leaf count"); compareMaps(inbuiltListener.leaves, "inbuilt", listener.leaves, "local"); compareMaps(listener.leaves, "local", inbuiltListener.leaves, "inbuilt"); }
static void SendServerMessage(string message) { try { TcpClient _client = new TcpClient("77.47.204.176", 85); byte[] data = System.Text.Encoding.ASCII.GetBytes(message); NetworkStream stream = _client.GetStream(); System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string)); ser.WriteObject(stream, message); //stream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); data = new byte[256]; string responseData = String.Empty; int bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); Console.WriteLine("Received {0}", responseData); stream.Close(); _client.Close(); } catch (ArgumentNullException e) { Console.WriteLine("Argument null exception: {0}", e.ToString()); } catch (SocketException e) { Console.WriteLine("Socket exception: {0}", e.ToString()); } Console.WriteLine("Message will send.."); }
private void DownloadJsonCompleted(object sender, DownloadStringCompletedEventArgs e) { progressBar1.Visibility = Visibility.Collapsed; try { whoisInfo Info; MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)); //MessageBox.Show(e.Result); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(whoisInfo)); Info = serializer.ReadObject(ms) as whoisInfo; ms.Close(); //MessageBox.Show(Info.name); base_info.DataContext = Info; total_info.Text = Info.total_infor; } catch (WebException we) { MessageBox.Show("网络连接异常"); } catch (Exception ex) { MessageBox.Show("暂时无法获取信息"); } }