当前位置: 首页>>代码示例>>C#>>正文


C# DataContractJsonSerializer.WriteObject方法代码示例

本文整理汇总了C#中System.Runtime.Serialization.Json.DataContractJsonSerializer.WriteObject方法的典型用法代码示例。如果您正苦于以下问题:C# DataContractJsonSerializer.WriteObject方法的具体用法?C# DataContractJsonSerializer.WriteObject怎么用?C# DataContractJsonSerializer.WriteObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Runtime.Serialization.Json.DataContractJsonSerializer的用法示例。


在下文中一共展示了DataContractJsonSerializer.WriteObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SerializeJsonDataContract

        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");
        }
开发者ID:michaljaros84,项目名称:OneBigPlayground,代码行数:27,代码来源:SerializeShit.cs

示例2: InfoBipSingleTextContainer

        /// <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);
            }
        }
开发者ID:karlbuhariwala,项目名称:ServiceMeRestService,代码行数:54,代码来源:PhoneVerificationProvider.cs

示例3: Main

        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();
        }
开发者ID:rmnblm,项目名称:mcsd,代码行数:30,代码来源:Program.cs

示例4: Main

        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();
        }
开发者ID:ssickles,项目名称:archive,代码行数:31,代码来源:client.cs

示例5: RegisterDevice

		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);
		}
开发者ID:tomasmcguinness,项目名称:AzureManager,代码行数:33,代码来源:AddSubscriptionViewModel.cs

示例6: Serialize

 /// <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);
 }
开发者ID:alastairwyse,项目名称:OraclePermissionGeneratorAndroid,代码行数:12,代码来源:ContainerObjectJsonSerializer.cs

示例7: ToJson

        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;
        }
开发者ID:ryanfiorini,项目名称:appMobiFacebookTemplate,代码行数:25,代码来源:JsonHelper.cs

示例8: ProcessRequest

        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);
            }
        }
开发者ID:mahuidong,项目名称:my-csharp-sample,代码行数:33,代码来源:JsonSearch.ashx.cs

示例9: OnPreRender

        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);
        }
开发者ID:maxpavlov,项目名称:FlexNet,代码行数:32,代码来源:AllowedChildTypes.cs

示例10: ConvertSelectedItemsToJson

        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);
        }
开发者ID:grbbod,项目名称:drconnect-jungo,代码行数:31,代码来源:ProductPickerController.cs

示例11: LoadUsers

        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();
        }
开发者ID:kyc30090,项目名称:slickgrid-ajax-sort,代码行数:28,代码来源:Frank.aspx.cs

示例12: SaveAppInfo

        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();
            }
        }
开发者ID:TroyBolton,项目名称:azure-mobile-services,代码行数:25,代码来源:AppInfoRepository.cs

示例13: Main

        static void Main(string[] args)
        {
            WebClient proxy = new WebClient();
            var result = proxy.DownloadData("http://localhost:62671/Service1.svc/Employee");
            Console.WriteLine(result);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<EmployeeDTO>));
            var lstEmp = (List<EmployeeDTO>) ser.ReadObject(new MemoryStream(result));
            foreach (var r in lstEmp)
            {
                Console.WriteLine(r.Name);
            }

            Console.ReadKey(true);
            var req  = (HttpWebRequest) WebRequest.Create("http://localhost:62671/Service1.svc/Employee");
            req.Method = "POST";
            req.ContentType = @"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);
        }
开发者ID:sarbjitc,项目名称:WCFCRUD,代码行数:32,代码来源:Program.cs

示例14: JsonOrJsonP

        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" };
            }
        }
开发者ID:groupdocs-annotation,项目名称:groupdocs-annotation-net-sample,代码行数:33,代码来源:ControllerExtensions.cs

示例15: SerializeObject

        ///<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;
            }
        }
开发者ID:pmizel,项目名称:DevMentor.Context.FileContext,代码行数:36,代码来源:JsonHelper.cs


注:本文中的System.Runtime.Serialization.Json.DataContractJsonSerializer.WriteObject方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。