public static void SerializeJsonDataContract(int houseNo = 0, string street = null, string desc = null) { Address ad = new Address { HouseNo = houseNo, Street = street, Desc = desc }; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Address)); using (FileStream fs = File.Open(@"c:\TestOutput\testJsonDataContractSerializer.js", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { ser.WriteObject(fs, ad); } //to json stream DataContractJsonSerializer using (MemoryStream ms = new MemoryStream()) using (StreamReader sr = new StreamReader(ms)) { ser.WriteObject(ms, ad); ms.Position = 0; Console.WriteLine(sr.ReadToEnd()); } //deserialize DataContractJsonSerializer using (FileStream fs = File.OpenRead(@"c:\TestOutput\testJsonDataContractSerializer.js")) { Address address = (Address)ser.ReadObject(fs); } Console.WriteLine("Finished SerializeJsonDataContract"); }
/// <summary> /// Sends the verification SMS. /// </summary> /// <param name="phone">The phone.</param> /// <param name="verificationCode">The verification code.</param> /// <exception cref="System.Exception">Error: + ex.Message</exception> void IPhoneVerificationProvider.SendVerificationSMS(string phone, string verificationCode) { InfoBipSingleTextContainer infoBipSingleTextContainer = new InfoBipSingleTextContainer(); infoBipSingleTextContainer.From = "ServiceMe"; infoBipSingleTextContainer.To = phone; infoBipSingleTextContainer.Text = string.Format("ServiceMe verification code is {0}", verificationCode); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.sendVerificationSmsUrl); request.Method = "POST"; request.ContentType = "application/json"; request.Headers.Add("Authorization", "Basic " + this.infoBipAuthorizationCode); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(InfoBipSingleTextContainer)); bool readNow = false; if (readNow) { MemoryStream memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, infoBipSingleTextContainer); memoryStream.Position = 0; StreamReader sr = new StreamReader(memoryStream); string jsonText = sr.ReadToEnd(); } using (Stream stream = request.GetRequestStream()) { serializer.WriteObject(stream, infoBipSingleTextContainer); } try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { if (readNow) { StreamReader sr = new StreamReader(responseStream); string jsonText = sr.ReadToEnd(); } } } } catch (Exception ex) { throw new Exception("Error: " + ex.Message); } }
public void WriteTo(object entity, IHttpEntity response, string[] paramneters) { if (entity == null) return; DataContractJsonSerializer serializer = new DataContractJsonSerializer(entity.GetType()); serializer.WriteObject(response.Stream, entity); }
public static string LoadUsers() { List<Person> users = new List<Person>(); using (SqlConnection conn = UtWeb.ConnectionGet()) { conn.Open(); SqlCommand command = new SqlCommand("UserGet", conn); using (SqlDataReader r = command.ExecuteReader()) { while (r.Read()) { Person person = new Person(); person.LoginName = r["LoginName"].ToString(); person.FirstName = r["FirstName"].ToString(); person.LastName = r["LastName"].ToString(); users.Add(person); } } } MemoryStream stream = new MemoryStream(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person[])); serializer.WriteObject(stream, users.ToArray()); stream.Position = 0; StreamReader streamReader = new StreamReader(stream); return streamReader.ReadToEnd(); }
/// <summary> /// Serialize object to String /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string Serialize <T>(T obj) { string result = null; MemoryStream ms = new MemoryStream(); try { DateTime startTime = DateTime.Now; /*System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = * new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType(), new List<Type>(), Int16.MaxValue, true, * new ZentoSurrogate(), false);*/ System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); serializer.WriteObject(ms, obj); result = Encoding.UTF8.GetString(ms.ToArray()); double time = (DateTime.Now - startTime).TotalSeconds; totalTimeExecution += time; } catch (Exception e) { LogHelper.LogError("exception while serializing : " + e.Message + " - " + e.StackTrace); throw e; } finally { ms.Dispose(); } return(result); }
public void ProcessRequest(HttpContext context) { int id = Convert.ToInt32(context.Request["id"]); mydbEntities1 db = new mydbEntities1(); user new1 = db.users.Single(u => u.id == id); db.DeleteObject(new1); db.SaveChanges(); var p1 = new result(); if (new1 != null) { p1.success = true; p1.msg = "aaa"; } else { p1.success = false; p1.msg = "Some errors occured."; } DataContractJsonSerializer json = new DataContractJsonSerializer(p1.GetType()); json.WriteObject(context.Response.OutputStream, p1); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; // 取得查询关键字. // 这里的 q 是 typeahead 的参数那里手工设定的, 可以根据需要修改. string queryKeyword = context.Request["q"]; // Jquery UI 传递的参数名称是 term // 这个 term 是默认值, 不需要手工指定. if (String.IsNullOrEmpty(queryKeyword)) { queryKeyword = context.Request["term"]; } var query = from data in TestCityData.testCityList where data.CityKeyword.Contains(queryKeyword) group data by data.CityName; List<string> result = query.Select(p=>p.Key).ToList(); // 构造 序列化类. DataContractJsonSerializer dcjs = new DataContractJsonSerializer(result.GetType()); using (MemoryStream st = new MemoryStream()) { // 写入数据流 dcjs.WriteObject(st, result); // 读取流, 并输出. byte[] buff = st.ToArray(); string jsonString = System.Text.Encoding.UTF8.GetString(buff); context.Response.Write(jsonString); } }
protected void Page_Load(object sender, EventArgs e) { Status.RecordHit(); String numFacesString = Request.QueryString["numFaces"]; int numFaces = numFacesString == null ? 20 : int.Parse(numFacesString); if (numFaces > 100) numFaces = 100; var faces = FacesLite.GetRandomFaces(numFaces).ToArray(); Message mess = new Message(); mess.FaceImages = new List<FaceImage>(); for (int i = 0; i < faces.Count(); i++) { FaceImage fi = new FaceImage() { ukey = faces[i].Item1, path = faces[i].Item2 }; mess.FaceImages.Add(fi); } DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FaceImage[])); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, mess.FaceImages.ToArray()); string json = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.Write(json); Response.End(); }
protected override void OnPreRender(EventArgs e) { if (!this.ReadOnlyMode && !UseBrowseTemplate) { string jsonData; using (var s = new MemoryStream()) { var workData = ContentType.GetContentTypes() .Select(n => new ContentTypeItem {value = n.Name, label = n.DisplayName, path = n.Path, icon = n.Icon}) .OrderBy(n => n.label); var serializer = new DataContractJsonSerializer(typeof (ContentTypeItem[])); serializer.WriteObject(s, workData.ToArray()); s.Flush(); s.Position = 0; using (var sr = new StreamReader(s)) { jsonData = sr.ReadToEnd(); } } // init control happens in prerender to handle postbacks (eg. pressing 'inherit from ctd' button) var contentTypes = _contentTypes ?? GetContentTypesFromControl(); InitControl(contentTypes); var inherit = contentTypes == null || contentTypes.Count() == 0 ? 0 : 1; UITools.RegisterStartupScript("initdropboxautocomplete", string.Format("SN.ACT.init({0},{1})", jsonData, inherit), this.Page); } base.OnPreRender(e); }
/// <summary> /// Serializes a list of OracleObjectPermissionSet objects to a JSON-encoded string. /// </summary> /// <param name="permissionSetArray">The list of OracleObjectPermissionSet objects to serialize.</param> /// <returns>The list serialized as a string.</returns> public String Serialize(List<Containers.OracleObjectPermissionSet> permissionSetArray) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Containers.OracleObjectPermissionSet>)); MemoryStream tempStream = new MemoryStream(); serializer.WriteObject(tempStream, permissionSetArray); return ConvertMemoryStreamToString(tempStream); }
/// <summary> /// Serializes a list of strings to a JSON-encoded string. /// </summary> /// <param name="strings">The list of strings to serialize.</param> /// <returns>The list serialized as a string.</returns> public String Serialize(List<String> strings) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<String>)); MemoryStream tempStream = new MemoryStream(); serializer.WriteObject(tempStream, strings); return ConvertMemoryStreamToString(tempStream); }
private void RegisterClick(object sender, RoutedEventArgs e) { if (UsernameField.Text == "" || PasswordField.Password == "" || ConfirmPasswordField.Password == "") { ErrorField.Text = "All fields are mandatory."; return; } if (PasswordField.Password != ConfirmPasswordField.Password) { ErrorField.Text = "Password and Confirmation don't match."; return; } ErrorField.Text = ""; APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Register, "register"); Dictionary<string, string> dict = new Dictionary<string, string>() { {"username", UsernameField.Text}, {"password", PasswordField.Password} }; var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); MemoryStream stream = new MemoryStream(); serializer.WriteObject(stream, dict); byte[] bytes = stream.ToArray(); string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length); request.Execute(null, content); }
public static string ToJson(this object obj) { if (obj == null) { return "null"; } DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, obj); ms.Position = 0; string json = String.Empty; using (StreamReader sr = new StreamReader(ms)) { json = sr.ReadToEnd(); } //ms.Close(); return json; }
//TODO: now it is assuming that the "generated" type name is the same, can we assume that? public IEnumerable<string> All(string typeName) { IProvider provider = ProviderConfiguration.GetProvider(typeName); Type type = provider.Type; IEnumerable objects = provider.All(); List<string> result = new List<string>(); foreach (var obj in objects) { using (MemoryStream stream = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(type); serializer.WriteObject(stream, obj); stream.Position = 0; using (StreamReader reader = new StreamReader(stream)) { result.Add(reader.ReadToEnd()); } } } return result; //return // "{ \"<Id>k__BackingField\": \"patients/1\", \"<Name>k__BackingField\": \"Margol Foo\",\"Name\": \"Margol Foo\"}"; }
private string ConvertSelectedItemsToJson(string selectedItems) { var sia = string.IsNullOrEmpty(selectedItems) ? new string[0] : selectedItems.Split(','); var currentContext = System.Web.HttpContext.Current; var products = sia.AsParallel().Select(pid => { long prodId; if (!long.TryParse(pid, out prodId)) return null; System.Web.HttpContext.Current = currentContext; var p = _catalogApi.GetProductAsync(_catalogApi.GetProductUri(prodId)).Result; if (p == null) return null; return new ProductEntityViewModel { Id = p.Id, Title = p.DisplayName, Description = p.ShortDescription }; }).Where(product => product != null).ToList(); var serializer = new DataContractJsonSerializer(typeof(ProductEntityViewModel[])); var ms = new MemoryStream(); serializer.WriteObject(ms, products.ToArray()); var json = ms.ToArray(); ms.Close(); return Encoding.UTF8.GetString(json, 0, json.Length); }
public void Save(List<ShapeData> balls, string FilePath) { DataContractJsonSerializer writer = new DataContractJsonSerializer(typeof(List<ShapeData>)); FileStream file = File.Create(FilePath); writer.WriteObject(file, balls); file.Close(); }
public static ActionResult JsonOrJsonP(this Controller controller, object data, string callback, bool serialize = true) { bool isJsonP = (controller.Request != null && controller.Request.HttpMethod == "GET"); string serializedData; if (isJsonP) { if (serialize) { using (var ms = new System.IO.MemoryStream()) { var serializer = new DataContractJsonSerializer(data.GetType()); serializer.WriteObject(ms, data); serializedData = System.Text.Encoding.UTF8.GetString(ms.ToArray()); } } else serializedData = (string) data; string serializedDataWithCallback = String.Format("{0}({1})", callback, serializedData); return new ContentResult { Content = serializedDataWithCallback, ContentType = "application/javascript" }; } if (serialize) { return new JsonDataContractActionResult(data); } else { serializedData = (string) data; return new ContentResult { Content = serializedData, ContentType = "application/json" }; } }
static void Main(string[] args) { WebClient proxy = new WebClient(); var result = proxy.DownloadData("http://*****:*****@"application/json;charset=utf-8"; EmployeeDTO emp = new EmployeeDTO {Name="Sachin T",City="Mumbai",Id="rt2"}; DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(EmployeeDTO)); MemoryStream mw = new MemoryStream(); var reader = new StreamReader(mw); ser1.WriteObject(mw,emp); mw.Position =0; var body = reader.ReadToEnd(); var strmWriter = new StreamWriter(req.GetRequestStream()); strmWriter.Write(body); var response = req.GetResponse(); //proxy.UploadString("",) //proxy.UploadData("http://localhost:62671/Service1.svc/Employee", "POST", mw.ToArray()); Console.WriteLine("Data Created"); Console.ReadKey(true); }
private async Task<HttpResponseMessage> EditUserCommit(int id, dynamic targetObject) { try { var person = (ProjectMemberContrainModel)targetObject; using (var ms = new MemoryStream()) { var djs = new DataContractJsonSerializer(typeof(ProjectMemberContrainModel)); djs.WriteObject(ms, person); ms.Position = 0; var sc = new StreamContent(ms); sc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var resp = id == -1 ? await HttpClient.PostAsync(new Uri(ApiRoot), sc) : await HttpClient.PutAsync(new Uri(ApiRoot + @"/" + id), sc); resp.EnsureSuccessStatusCode(); return resp; } } catch (Exception ex) { LogManager.Instance.LogException(ex.ToString()); return new HttpResponseMessage(HttpStatusCode.NotModified); } }
public async Task SaveAppInfo(SavedAppInfo appInfo) { Exception ex = null; this.savedAppInfo = appInfo; try { var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(SavedAppsFileName, CreationCollisionOption.ReplaceExisting); using (var stream = await file.OpenStreamForWriteAsync()) { DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(SavedAppInfo)); dcjs.WriteObject(stream, appInfo); } } catch (Exception e) { ex = e; } if (ex != null) { await new MessageDialog( string.Format("{0}: {1}", ex.GetType().FullName, ex.Message), "Error saving app info").ShowAsync(); } }
///<summary> /// Method to convert a custom Object to JSON string /// </summary> /// <param name="pObject">Object that is to be serialized to JSON</param> /// <param name="objectType"></param> /// <returns>JSON string</returns> public static String SerializeObject(Object pobject, Type objectType) { try { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o"); var jsonSerializer = new DataContractJsonSerializer(objectType, settings); //jsonSerializer.DateTimeFormat. string returnValue = ""; using (var memoryStream = new MemoryStream()) { using (var xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream)) { jsonSerializer.WriteObject(xmlWriter, pobject); xmlWriter.Flush(); returnValue = Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); } } return returnValue; } catch (Exception e) { throw e; } }
public void ProcessRequest(HttpContext context) { var Re = new ReturnDate(); mydbEntities1 db = new mydbEntities1(); var query = from p in db.users select p; List<person> new1 = new List<person>(); foreach (var q in query) { person p1 = new person(); p1.id = q.id; p1.firstname = q.firstname; p1.lastname = q.lastname; p1.phone = q.phone; p1.email = q.email; new1.Add(p1); } Re.total = new1.Count.ToString(); Re.rows = new1; DataContractJsonSerializer json = new DataContractJsonSerializer(Re.GetType()); json.WriteObject(context.Response.OutputStream, Re); }
/// <summary> /// 演示DataContractJsonSerializer的序列化和反序列化 /// </summary> void ShowDataContractJsonSerializer() { var dataContractJsonSerializerObject = new API.DataContractJsonSerializerObject { ID = Guid.NewGuid(), Name = "DataContractJsonSerializer", Age = 28, Time = DateTime.Now }; var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(API.DataContractJsonSerializerObject)); // 序列化 var ms = new MemoryStream(); serializer.WriteObject(ms, dataContractJsonSerializerObject); ms.Position = 0; var sr = new StreamReader(ms); var str = sr.ReadToEnd(); txtDataContractJsonSerializer.Text = str; // 反序列化 var buffer = System.Text.Encoding.UTF8.GetBytes(str); var ms2 = new MemoryStream(buffer); var dataContractJsonSerializerObject2 = serializer.ReadObject(ms2) as API.DataContractJsonSerializerObject; lblDataContractJsonSerializer.Text = dataContractJsonSerializerObject2.Name; }
public override void Serialize(object data, Stream output) { // what if data is null? var serializer = new DataContractJsonSerializer(data.GetType()); serializer.WriteObject(output, data); }
private static void JsonSerializationDemo() { Header("JSON сериализация"); TrainJson train = new TrainJson{ Speed = 190.2, Length = 8, Travellers = new[] {"Иванов И.И.", "Петров П.П.", "Сидоров С.С."}}; Comment("Объект до сериализации"); train.Print(); Console.WriteLine(); using (MemoryStream memoryStream = new MemoryStream()) { // Выполняем сериализацию в поток в памяти DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TrainJson)); serializer.WriteObject(memoryStream, train); // Печатаем результат на экран memoryStream.Position = 0; StreamReader reader = new StreamReader(memoryStream); string json = reader.ReadToEnd(); Comment("Результат JSON сериализации"); Console.WriteLine(json); Console.WriteLine(); memoryStream.Position = 0; // Выполняем десериализацию TrainJson trainCopy = (TrainJson)serializer.ReadObject(memoryStream); Comment("Копия объекта после сериализации."); trainCopy.Print(); Console.WriteLine("\r\nReferenceEquals(train, trainCopy)={0}", ReferenceEquals(train, trainCopy)); reader.Close(); } Pause(); }
public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.ContentType = "text/json"; response.ContentEncoding = Encoding.UTF8; var serializer = new DataContractJsonSerializer(value.GetType()); serializer.WriteObject(response.OutputStream, value); }
private void run() { try { var sysinfoJsonSerializer = new DataContractJsonSerializer(typeof(Sysinfo)); var sysinfoJsonStream = new MemoryStream(); var systeminfo = new Sysinfo(); sysinfoJsonSerializer.WriteObject(sysinfoJsonStream, systeminfo); sysinfoJsonStream.Position = 0; var sysinfoJsonReader = new StreamReader(sysinfoJsonStream); string sysinfoJson = sysinfoJsonReader.ReadToEnd(); var ht = new Hashtable { {"id", BmclCore.Config.Username}, {"sysinfo", sysinfoJson}, {"version", BmclCore.BmclVersion} }; string postdata = ParsToString(ht); var req = (HttpWebRequest)WebRequest.Create("http://www.bangbang93.com/bmcl/bmcllog.php"); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] buffer = Encoding.UTF8.GetBytes(postdata); req.ContentLength = buffer.Length; var s = req.GetRequestStream(); s.Write(buffer, 0, buffer.Length); s.Close(); req.GetResponse(); } catch (Exception ex) { Logger.Log(ex); } }
// GET: api/FoodStuffs public string Get() { if (User.Identity.GetUserId() != null) { var _UserId = User.Identity.GetUserId(); var users = _foodstuffsRepo.Get(x => x.User == null || x.User.UserId == _UserId); MemoryStream stream = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(IEnumerable<FoodStuffs>)); ser.WriteObject(stream, users); stream.Position = 0; StreamReader sr = new StreamReader(stream); return sr.ReadToEnd(); } else { var users = _foodstuffsRepo.Get(x => x.User == null); MemoryStream stream = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(IEnumerable<FoodStuffs>)); ser.WriteObject(stream, users); stream.Position = 0; StreamReader sr = new StreamReader(stream); return sr.ReadToEnd(); } }
public void RegisterDevice(object state) { IsRegistering = true; HttpNotificationChannel pushChannel; pushChannel = HttpNotificationChannel.Find("RegistrationChannel"); if (pushChannel == null) { pushChannel = new HttpNotificationChannel("RegistrationChannel"); } RegistrationRequest req = new RegistrationRequest() { ChannelUri = pushChannel.ChannelUri.ToString(), DeviceType = (short)Common.Data.DeviceType.WindowsPhone7 }; string json = null; using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RegistrationRequest)); serializer.WriteObject(ms, req); json = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length); } WebClient registrationClient = new WebClient(); registrationClient.Headers["content-type"] = "application/json"; registrationClient.UploadStringCompleted += registrationClient_UploadStringCompleted; string url = string.Format("http://{0}/Services/RegisterDevice", App.ServiceHostName); registrationClient.UploadStringAsync(new Uri(url), json); }
static void Main() { Person p = new Person(); p.name = "John"; p.age = 42; MemoryStream stream1 = new MemoryStream(); //Serialize the Person object to a memory stream using DataContractJsonSerializer. DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person)); ser.WriteObject(stream1, p); //Show the JSON output. stream1.Position = 0; StreamReader sr = new StreamReader(stream1); Console.Write("JSON form of Person object: "); Console.WriteLine(sr.ReadToEnd()); //Deserialize the JSON back into a new Person object. stream1.Position = 0; Person p2 = (Person)ser.ReadObject(stream1); //Show the results. Console.Write("Deserialized back, got name="); Console.Write(p2.name); Console.Write(", age="); Console.WriteLine(p2.age); Console.WriteLine("Press <ENTER> to terminate the program."); Console.ReadLine(); }
static void Main(string[] args) { MemoryStream stream = new MemoryStream(); //Simple feed with sample data SyndicationFeed feed = new SyndicationFeed("Custom JSON feed", "A Syndication extensibility sample", null); feed.LastUpdatedTime = DateTime.Now; feed.Items = from s in new string[] { "hello", "world" } select new SyndicationItem() { Summary = SyndicationContent.CreatePlaintextContent(s) }; //Write the feed out to a MemoryStream as JSON DataContractJsonSerializer writeSerializer = new DataContractJsonSerializer(typeof(JsonFeedFormatter)); writeSerializer.WriteObject(stream, new JsonFeedFormatter(feed)); stream.Position = 0; //Read in the feed using the DataContractJsonSerializer DataContractJsonSerializer readSerializer = new DataContractJsonSerializer(typeof(JsonFeedFormatter)); JsonFeedFormatter formatter = readSerializer.ReadObject(stream) as JsonFeedFormatter; SyndicationFeed feedRead = formatter.Feed; //Dump the JSON stream to the console string output = Encoding.UTF8.GetString(stream.GetBuffer()); Console.WriteLine(output); Console.ReadLine(); }
static void Main(string[] args) { if (File.Exists(filename)) File.Delete(filename); Animal a = new Animal() { Name = "Roman", NumberOfLegs = 2 }; Console.WriteLine("Original"); Console.WriteLine(a.ToString()); FileStream writeStream = File.Create(filename); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Animal)); serializer.WriteObject(writeStream, a); writeStream.Close(); Console.WriteLine("Contents of " + filename); Console.WriteLine(File.ReadAllText(filename)); FileStream readStream = File.OpenRead(filename); Animal deserialized = (Animal)serializer.ReadObject(readStream); Console.WriteLine("Deserialized"); Console.WriteLine(deserialized.ToString()); Console.ReadKey(); }
/// <summary> /// This Function is used to write the Missing Targets Vs Missing Business Class Data Passed to corresponding FilePath /// </summary> /// <param name="LoginId"></param> /// <param name="MissingTargetsVsBusinessClass"></param> private void WriteMissingTargetsVsBusinessClassChartCacheFile(string LoginId, List <MissingTargetsVsBusinessClass> MissingTargetsVsBusinessClass) { const string FUNCTION_NAME = "WriteMissingTargetsVsBusinessClassChartCacheFile"; SICTLogger.WriteInfo(CLASS_NAME, FUNCTION_NAME, "Start for LoginId -" + LoginId); try { DepartureFormBusiness ObjDepartureFormBusiness = new DepartureFormBusiness(); BusinessUtil ObjBusinessUtil = new BusinessUtil(); string FilePath = string.Empty; string FolderPath = string.Empty; string MissingTargetsandBusinessClassData = string.Empty; ObjBusinessUtil.GetMissingTargetsVsBusinessClassChartsFilePath(LoginId, ref FilePath, ref FolderPath); Boolean IsFolderExists = System.IO.Directory.Exists(FolderPath); if (!IsFolderExists) { System.IO.Directory.CreateDirectory(FolderPath); } SICTLogger.WriteVerbose(CLASS_NAME, FUNCTION_NAME, "MissingTargetsVsBusinessClass Charts cache file for AirportLoginId- " + LoginId); using (var MemoryStream = new MemoryStream()) { var Serlizer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <MissingTargetsVsBusinessClass>)); Serlizer.WriteObject(MemoryStream, MissingTargetsVsBusinessClass); MissingTargetsandBusinessClassData = System.Text.Encoding.UTF8.GetString(MemoryStream.GetBuffer(), 0, Convert.ToInt32(MemoryStream.Length)); ObjDepartureFormBusiness.WriteToFile(MissingTargetsandBusinessClassData, FilePath); } } catch (Exception Ex) { SICTLogger.WriteException(CLASS_NAME, FUNCTION_NAME, Ex); } SICTLogger.WriteInfo(CLASS_NAME, FUNCTION_NAME, "End for LoginId -" + LoginId); }
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; }
///// <summary> ///// JSON字符串转化为对象 ///// </summary> ///// <param name="obj"></param> ///// <returns></returns> //public static T ToObject<T>(this string obj) //{ // JavaScriptSerializer Serializer = new JavaScriptSerializer(); // return Serializer.Deserialize<T>(obj); //} /// <summary> /// 对象转化为JSON字符串 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string Serialize <T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); System.IO.MemoryStream ms = new System.IO.MemoryStream(); serializer.WriteObject(ms, obj); string retVal = System.Text.Encoding.UTF8.GetString(ms.ToArray()); ms.Dispose(); return(retVal); }
public static string To <T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); string retVal = Encoding.Default.GetString(ms.ToArray()); } return(retVal); }
private string JsonSerializer <T>(T t) { System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); ser.WriteObject(ms, t); string jsonString = System.Text.Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return(jsonString); }
public static string GetJsonString <T>(T value) { System.Runtime.Serialization.Json.DataContractJsonSerializer json = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); MemoryStream stream = new MemoryStream(); json.WriteObject(stream, value); string str = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return(str); }
public void Active() { string url = @"http://localhost:59533/Service1.svc/GetR"; B bObj = new B(); bObj.s2 = "StringToSend"; // var json = new JavaScriptSerializer().Serialize(bObj); string json; using (var ms = new MemoryStream()) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(B)); ser.WriteObject(ms, bObj); json = System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length)); } json = "{a:b}"; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "text/plain"; byte[] byteArray = Encoding.UTF8.GetBytes(json); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); // ASCIIEncoding encoding = new ASCIIEncoding(); // byte[] byteArray = encoding.GetBytes(json); dataStream.Write(byteArray, 0, byteArray.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string result; using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data)) { result = reader.ReadToEnd(); } } catch (Exception exp) { string s = exp.Message; } }
public string ToJsonString() { var dk = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType()); var ms = new MemoryStream(); dk.WriteObject(ms, this); var rdr = new StreamReader(ms); ms.Position = 0; return(rdr.ReadToEnd()); }
public static string ToJson <T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer ds = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ds.WriteObject(ms, obj); string strJSON = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return(strJSON); }
static void Main() { var z = new Person() { Name = "Taro", Age = 18, Type = "Student" }; var ds = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Person)); using (var sw = File.Create("test.json")) ds.WriteObject(sw, z); System.Console.WriteLine(File.ReadAllText("test.json")); }
/// <summary> /// List<T>转Json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns></returns> public static string Obj2Json <T>(T data) { try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, data); return(Encoding.UTF8.GetString(ms.ToArray())); } } catch { return(null); } }
public static void Serialize(Stream s, object value) { if (value == null || s == null) { throw new ArgumentNullException(); } if (!s.CanWrite) { throw new ArgumentNullException(); } R.DataContractJsonSerializer serializer = new R.DataContractJsonSerializer(value.GetType()); serializer.WriteObject(s, value); }
public static string ToJsonDcJs <T>(this T item, System.Text.Encoding encoding = null, System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = null) { encoding = encoding ?? Encoding.Default; serializer = serializer ?? new DataContractJsonSerializer(typeof(T)); using (var stream = new System.IO.MemoryStream()) { serializer.WriteObject(stream, item); var json = encoding.GetString((stream.ToArray())); return(json); } }
public string Serialize <T>(object objectToSerialize, Encoding encoding) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); var ms = new MemoryStream(); ser.WriteObject(ms, objectToSerialize); string str = encoding.GetString(ms.ToArray()); ms.Close(); ms.Dispose(); return(str); }
/// <summary> /// 序列化 /// </summary> /// <param name="instance"></param> /// <returns></returns> public static string Parse(object instance) { if (instance != null) { using (var ms = new MemoryStream()) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(instance.GetType()); ser.WriteObject(ms, instance); return(System.Text.Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length)); } } return(null); }
private void AppendProjects(List <AgentProjectInfo> projects, StringBuilder postString) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <AgentProjectInfo>)); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, projects); String json = Encoding.Default.GetString(ms.ToArray()); postString.Append("&"); postString.AppendFormat("{0}={1}", APIConstants.PARAM_DIFF, System.Web.HttpUtility.UrlEncode(json)); Debug("AgentProjectInfo JSON: " + json); DebugAgentProjectInfos(projects); }
/// <summary> /// 将实体对象转换成json对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static string ObjectToJsonString <T>(T t) { try { System.Runtime.Serialization.Json.DataContractJsonSerializer json = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, t); return(System.Text.Encoding.UTF8.GetString(stream.ToArray())); } } catch { } return(null); }
public override string ToString() { JSON jsonSerializer; MemoryStream memoryStream; StreamReader streamReader; memoryStream = new MemoryStream(); jsonSerializer = new JSON(typeof(Pacote)); jsonSerializer.WriteObject(memoryStream, this); memoryStream.Position = 0; streamReader = new StreamReader(memoryStream); return(streamReader.ReadToEnd()); }
// NOTE: // [DataMember(Name="xxx")] and [IgnoreDataMember] attribute is valid. #region Method public static string Serialize <T>(T obj) { var memoryStream = new MemoryStream(); var streamReader = new StreamReader(memoryStream); var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); serializer.WriteObject(memoryStream, obj); memoryStream.Position = 0; string json = streamReader.ReadToEnd(); memoryStream.Dispose(); streamReader.Dispose(); return(json); }
public static string Serialize(object objForSerialization) { string str = string.Empty; if (objForSerialization == null) { return(str); } System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(objForSerialization.GetType()); using (MemoryStream stream = new MemoryStream()) { serializer.WriteObject(stream, objForSerialization); byte[] buffer = new byte[stream.Length]; stream.Position = 0L; stream.Read(buffer, 0, buffer.Length); return(buffer.ToString()); } }
/// <summary>Serializes the specified object as a JSON string</summary> /// <param name="objectToSerialize">Specified object to serialize</param> /// <returns>JSON string of serialzied object</returns> private static string Serialize(object objectToSerialize) { using (System.IO.MemoryStream _Stream = new System.IO.MemoryStream()) { try { var _Serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(objectToSerialize.GetType()); _Serializer.WriteObject(_Stream, objectToSerialize); _Stream.Position = 0; System.IO.StreamReader _Reader = new System.IO.StreamReader(_Stream); return(_Reader.ReadToEnd()); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Serialize:" + e.Message); return(string.Empty); } } }
public static string GetJSON <T>(object obj) { string result = String.Empty; try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { serializer.WriteObject(ms, obj); result = System.Text.Encoding.UTF8.GetString(ms.ToArray()); } } catch (Exception ex) { throw ex; } return(result); }
/// <summary> /// C#のデータからJson形式の文字列に変換する /// </summary> /// <typeparam name="T">内部データ型</typeparam> /// <param name="data">シリアライズ化対象の内部データ型データコレクション</param> /// <returns>Json形式の文字列</returns> public static string FromData <T>(T data) where T : IJsonData { try { MemoryStream strm = new MemoryStream(); System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); ser.WriteObject(strm, data); strm.Position = 0; StreamReader sr = new StreamReader(strm); string jsontext = sr.ReadToEnd(); return(jsontext); } catch (Exception ex) { throw new WebAPIFormatException(string.Format("{0}をJson形式にシリアライズ化できません。", typeof(T)), ex); } finally { } }
/// <summary> /// 转换List<T>的数据为JSON格式 /// </summary> /// <typeparam name="T">类</typeparam> /// <param name="vals">列表值</param> /// <returns>JSON格式数据</returns> public static string JSON <T>(List <T> vals) { System.Text.StringBuilder st = new System.Text.StringBuilder(); try { System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); foreach (T city in vals) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { s.WriteObject(ms, city); st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray())); } } } catch (Exception ex) { throw ex; } return(st.ToString()); }
private void SaveProject(bool force) { var saveData = ProTeGe.ProjectManager.Save(); var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ProTeGe.ProjectSaveInfo)); if (CheckDirectoryExists() == false) { return; } if (inputFieldFileName.text == "") { labelError.text = "file name can not be empty"; panelError.SetActive(true); return; } if (inputFieldFileName.text [0] == '.') { labelError.text = "file name can not start with a dot"; panelError.SetActive(true); return; } var filePath = curPath + @"\" + inputFieldFileName.text; if (filePath.Length >= 4) { if (filePath.Substring(filePath.Length - 4, 4) != ".ptg") { if (filePath.Substring(filePath.Length - 1) != ".") { filePath += "."; } filePath += "ptg"; } } else { if (filePath.Substring(filePath.Length - 1) != ".") { filePath += "."; } filePath += "ptg"; } FileInfo fileInfo; try{ fileInfo = new FileInfo(filePath); } catch { labelError.text = "file with this name could not be created"; panelError.SetActive(true); return; } if (force == false) { if (fileInfo.Exists) { labelOverwriteWarning.text = "file will be overwritten:\n\n" + fileInfo.FullName; overwriteWarning.SetActive(true); return; } } try{ using (FileStream stream = new FileStream(fileInfo.FullName, FileMode.Create)){ serializer.WriteObject(stream, saveData); } }catch { ShowErrorFileSave(); } lastFileName = inputFieldFileName.text; Globals.instance.components.dialogManager.CloseDialog(); }
public void Save() { using (Stream stream = File.Open(saveDirectory, FileMode.Create)) serializer.WriteObject(stream, Options); }
public void Save() { using (Stream stream = File.Open($"{AppDomain.CurrentDomain.BaseDirectory}\\{_ownTitle}.config.json", FileMode.Create)) serializer.WriteObject(stream, Options); }