Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
Inheritance: JsonWriter
Esempio n. 1
1
	private string CreateStatusText()
	{
		using (var sw = new StringWriter())
		using (var jsonWriter = new JsonTextWriter(sw))
		{
			jsonWriter.WriteStartObject();
			{
				// Login
				jsonWriter.WritePropertyName("login");
				jsonWriter.WriteStartObject();
				{
					jsonWriter.WritePropertyName("port");
					jsonWriter.WriteValue(LoginServer.Instance.Conf.Login.Port);
				}
				jsonWriter.WriteEndObject();

				// Servers
				jsonWriter.WritePropertyName("servers");
				jsonWriter.WriteStartObject();
				{
					foreach (var server in LoginServer.Instance.ServerList.List)
					{
						// Channels
						jsonWriter.WritePropertyName(server.Name);
						jsonWriter.WriteStartObject();
						{
							foreach (var channel in server.Channels)
							{
								// Channel
								jsonWriter.WritePropertyName(channel.Key);
								jsonWriter.WriteStartObject();
								{
									jsonWriter.WritePropertyName("host");
									jsonWriter.WriteValue(channel.Value.Host);

									jsonWriter.WritePropertyName("port");
									jsonWriter.WriteValue(channel.Value.Port);

									jsonWriter.WritePropertyName("online");
									jsonWriter.WriteValue(channel.Value.Users);

									jsonWriter.WritePropertyName("onlineMax");
									jsonWriter.WriteValue(channel.Value.MaxUsers);

									jsonWriter.WritePropertyName("state");
									jsonWriter.WriteValue(channel.Value.State);
								}
								jsonWriter.WriteEndObject();
							}
						}
						jsonWriter.WriteEndObject();
					}
				}
				jsonWriter.WriteEndObject();
			}
			jsonWriter.WriteEndObject();

			return sw.ToString();
		}
	}
Esempio n. 2
0
 private void PlayerEvents_LoadedGame(object sender, EventArgsLoadedGameChanged e)
 {
     try
     {
         Save_Anywhere_V2.Save_Utilities.Player_Utilities.load_player_info();
         Save_Anywhere_V2.Save_Utilities.Config_Utilities.DataLoader_Settings();
         Save_Anywhere_V2.Save_Utilities.Config_Utilities.MyWritter_Settings();
         //
     }
     catch (Exception ex)
     {
         try
         {
             Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
             serializer.NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore;
             serializer.TypeNameHandling      = Newtonsoft.Json.TypeNameHandling.All;
             serializer.Formatting            = Newtonsoft.Json.Formatting.Indented;
             serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
             using (StreamWriter sw = new StreamWriter(Path.Combine(Error_Path, "Mod_State.json")))
             {
                 using (Newtonsoft.Json.JsonWriter writer2 = new Newtonsoft.Json.JsonTextWriter(sw))
                 {
                     serializer.Serialize(writer2, this, typeof(Save_Anywhere_V2.Mod_Core));
                 }
             }
         }
         catch (Exception exc)
         {
             Log.Info(exc);
         }
         Stardew_Omegasis_Utilities.Mod.Error_Handling.Log_Error(new List <string>(), ex);
     }
 }
Esempio n. 3
0
 private void ShippingCheck(object sender, EventArgs e)
 {
     try
     {
         if (Game1.activeClickableMenu != null)
         {
             return;
         }
         Save_Anywhere_V2.Save_Utilities.GameUtilities.shipping_check();
     }
     catch (Exception ex)
     {
         try
         {
             Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
             serializer.NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore;
             serializer.TypeNameHandling      = Newtonsoft.Json.TypeNameHandling.All;
             serializer.Formatting            = Newtonsoft.Json.Formatting.Indented;
             serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
             using (StreamWriter sw = new StreamWriter(Path.Combine(Error_Path, "Mod_State.json")))
             {
                 using (Newtonsoft.Json.JsonWriter writer2 = new Newtonsoft.Json.JsonTextWriter(sw))
                 {
                     serializer.Serialize(writer2, this, typeof(Save_Anywhere_V2.Mod_Core));
                 }
             }
         }
         catch (Exception exc)
         {
             Log.Info(exc);
         }
         Stardew_Omegasis_Utilities.Mod.Error_Handling.Log_Error(new List <string>(), ex);
     }
 }
Esempio n. 4
0
        /// <summary>
        /// Writes Protocol in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        internal void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names)
        {
            writer.WriteStartObject();

            JsonHelper.writeIfNotNullOrEmpty(writer, "protocol", this.Name);
            JsonHelper.writeIfNotNullOrEmpty(writer, "namespace", this.Namespace);
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

            writer.WritePropertyName("types");
            writer.WriteStartArray();

            foreach (Schema type in this.Types)
            {
                type.WriteJson(writer, names, this.Namespace);
            }

            writer.WriteEndArray();

            writer.WritePropertyName("messages");
            writer.WriteStartObject();

            foreach (KeyValuePair <string, Message> message in this.Messages)
            {
                writer.WritePropertyName(message.Key);
                message.Value.writeJson(writer, names, this.Namespace);
            }

            writer.WriteEndObject();
            writer.WriteEndObject();
        }
Esempio n. 5
0
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            byte[] body;
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                        serializer.Serialize(writer, result);
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }

            Message replyMessage = null; // Message.CreateMessage(messageVersion, operation.Messages[1].Action, new RawBodyWriter(body));

            replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            HttpResponseMessageProperty respProp = new HttpResponseMessageProperty();

            respProp.Headers[HttpResponseHeader.ContentType] = "application/json";
            replyMessage.Properties.Add(HttpResponseMessageProperty.Name, respProp);
            return(replyMessage);
        }
Esempio n. 6
0
        /// <summary>
        /// Create new JSON data with the original and name value list.
        /// </summary>
        /// <param name="json">The original JSON data.</param>
        /// <param name="nameValues">The name values to add to the JSON data.</param>
        /// <returns>The new JSON data.</returns>
        public string Create(string json, JsonNameValue[] nameValues)
        {
            // Using string builder.
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            // Create the writer.
            using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.WriteStartObject();
                writer.WriteRaw(json.Trim(new char[] { '{', '}' }) + ",");

                // For each name value pair.
                foreach (JsonNameValue item in nameValues)
                {
                    writer.WritePropertyName(item.Name);
                    writer.WriteValue(item.Value);
                }

                // Write the end object.
                writer.WriteEndObject();
            }

            // Return the JSON data.
            return(sb.ToString());
        }
		static string GetJsonString(object obj)
		{
			using (var memoryStream = new MemoryStream())
			using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8))
			{
				using (var jsonTextWriter = new JsonTextWriter(streamWriter)
					{
						Formatting = Formatting.None
					})
				{
					var jsonSerializer = new JsonSerializer
						{
							Converters =
								{
									new JsonEnumConverter()
								},
						};

					jsonSerializer.Serialize(jsonTextWriter, obj);
				}
				streamWriter.Flush();

				return Encoding.UTF8.GetString(memoryStream.ToArray());
			}
		}
Esempio n. 8
0
        public void Dump()
        {
            try
            {
                var schema = this.CurrentSchema;
                ContentRepository.ChangeProblems.Do(cp => schema.ApplyProblem(this.LastSchema, cp));

                DirectoryInfo di = new DirectoryInfo(Paths.AppDataPath + "\\ContentSchema");
                if (!di.Exists)
                    di.Create();
                FileInfo fi = new FileInfo(Paths.AppDataPath + "\\ContentSchema\\LastSchema.json");
                var sz = new JsonSerializer();
                sz.Formatting = Formatting.Indented;
                using (var stream = fi.OpenWrite())
                using (var writer = new StreamWriter(stream))
                using (var jsonTextWriter = new JsonTextWriter(writer))
                {
                    sz.Serialize(writer, schema);
                }
            }
            catch (Exception ex)
            {
                log.Error("Error creating content schema module dump: ", ex);
            }
        }
Esempio n. 9
0
		public override void Execute(object parameter)
		{
			var saveFile = new SaveFileDialog
						   {
							   /*TODO, In Silverlight 5: DefaultFileName = string.Format("Dump of {0}, {1}", ApplicationModel.Database.Value.Name, DateTimeOffset.Now.ToString()), */
							   DefaultExt = ".raven.dump",
							   Filter = "Raven Dumps|*.raven.dump",
						   };

			if (saveFile.ShowDialog() != true)
				return;

			stream = saveFile.OpenFile();
			gZipStream = new GZipStream(stream, CompressionMode.Compress);
			streamWriter = new StreamWriter(gZipStream);
			jsonWriter = new JsonTextWriter(streamWriter)
						 {
							 Formatting = Formatting.Indented
						 };

			output(String.Format("Exporting to {0}", saveFile.SafeFileName));

			output("Begin reading indexes");

			jsonWriter.WriteStartObject();
			jsonWriter.WritePropertyName("Indexes");
			jsonWriter.WriteStartArray();

			ReadIndexes(0).Catch(exception => Infrastructure.Execute.OnTheUI(() => Finish(exception)));
		}
        protected virtual object ReadJsonAsStringArray(JsonReader reader)
        {
            if (reader.TokenType != JsonToken.StartArray)
            {
                reader.Skip();
                return null;
            }

            var rowValues = new List<string>();
            var valueStartDepth = reader.Depth;
            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
            {
                using (var jw = new JsonTextWriter(sw))
                {
                    while (reader.Read() && !(reader.TokenType == JsonToken.EndArray && reader.Depth == valueStartDepth))
                    {
                        jw.WriteToken(reader, true);
                        rowValues.Add(sb.ToString());
                        sb.Clear();
                    }
                }
            }

            return rowValues.ToArray();
        }
        private static string ExportJson(IEnumerable<SpriteFragment> fragments, string imageFile)
        {
            var map = new
            {
                images = fragments.Select(fragment =>
                {
                    var item = new
                    {
                        Name = Path.GetFileName(fragment.FileName),
                        Width = fragment.Width,
                        Height = fragment.Height,
                        OffsetX = fragment.X,
                        OffsetY = fragment.Y,
                    };

                    return item;
                })
            };

            string outputFile = GetFileName(imageFile, ExportFormat.Json);
            ProjectHelpers.CheckOutFileFromSourceControl(outputFile);

            using (StreamWriter sw = new StreamWriter(outputFile))
            using (JsonWriter jw = new JsonTextWriter(sw))
            {
                jw.Formatting = Formatting.Indented;

                var serializer = new JsonSerializer();
                serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
                serializer.Serialize(jw, map);
            }

            return outputFile;
        }
Esempio n. 12
0
        public static void WriteTo(this SecsMessage msg, JsonTextWriter jwtr)
        {
            jwtr.WriteStartObject();

            jwtr.WritePropertyName(nameof(msg.S));
            jwtr.WriteValue(msg.S);

            jwtr.WritePropertyName(nameof(msg.F));
            jwtr.WriteValue(msg.S);

            jwtr.WritePropertyName(nameof(msg.ReplyExpected));
            jwtr.WriteValue(msg.ReplyExpected);

            jwtr.WritePropertyName(nameof(msg.Name));
            jwtr.WriteValue(msg.Name);

            if (msg.SecsItem != null)
            {
                jwtr.WritePropertyName(nameof(msg.SecsItem));
                msg.SecsItem.WriteTo(jwtr);
            }

            jwtr.WriteEndObject();

            jwtr.Flush();
        }
Esempio n. 13
0
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     var s = new StringWriter();
     var w = new JsonTextWriter(s);
     base.WriteJson(w, value, serializer);
     writer.WriteValue(s.ToString().ToLower().Trim('"'));
 }
Esempio n. 14
0
        private void SelectEmailExist()
        {
            string email = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["email"]))
            {
                email = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["email"]));
            }
            int result = userBll.SelectEmailExist(email);

            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            if (result == 0)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("500");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Esempio n. 15
0
        private void GetUserInfoHead()
        {
            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            string username = userMethod.CheckUserIndentity_Username();

            if (username.Trim() != "")
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("username");
                writer.WriteValue(username);
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("username");
                writer.WriteValue("");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Esempio n. 16
0
        public static void WriteTo(this Item item, JsonTextWriter writer)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(item.Format));
            writer.WriteValue(Enum.GetName(typeof(SecsFormat), item.Format));
            if (item.Format == SecsFormat.List)
            {
                writer.WritePropertyName(nameof(item.Items));
                writer.WriteStartArray();
                foreach (var subitem in item.Items)
                    subitem.WriteTo(writer);
                writer.WriteEndArray();
            }
            else
            {
                writer.WritePropertyName(nameof(item.Values));

                if (item.Format == SecsFormat.ASCII || item.Format == SecsFormat.JIS8)
                {
                    writer.WriteValue(item.GetValue<string>());
                }
                else
                {
                    writer.WriteStartArray();
                    foreach (var value in item.Values)
                        writer.WriteValue(value);
                    writer.WriteEndArray();
                }
            }
            writer.WriteEndObject();
        }
Esempio n. 17
0
        private static void Test <T>(T obj)
        {
            var expected = NJ.JsonConvert.SerializeObject(obj);
            var actual   = JsonConvert.Serialize(obj);

            Assert.Equal(expected, actual);

            // Test deserialization
            var deserialziedObj     = JsonConvert.Deserialize <T>(actual);
            var deserializedObjJson = JsonConvert.Serialize(deserialziedObj);

            Assert.Equal(actual, deserializedObjJson);

            // Test formatting
            using (var stream = new MemoryStream())
            {
                using (var sw = new StreamWriter(stream))
                    using (var writer = new NJ.JsonTextWriter(sw))
                    {
                        writer.Formatting  = NJ.Formatting.Indented;
                        writer.Indentation = 4;
                        writer.IndentChar  = ' ';

                        var serializer = NJ.JsonSerializer.CreateDefault();

                        serializer.Serialize(writer, obj);
                    }

                expected = Encoding.UTF8.GetString(stream.ToArray());
            }
            actual = JsonConvert.Serialize(obj, JsonFormat.Indented);

            Assert.Equal(expected, actual);
        }
Esempio n. 18
0
        public static Message FormatObjectAsMessage(object obj, MessageVersion messageVersion, string action, HttpStatusCode statusCode)
        {
            byte[] body;
            var    serializer = new JsonSerializer();

            serializer.Converters.Add(new StringEnumConverter {
                AllowIntegerValues = false, CamelCaseText = false
            });

            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        //writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                        serializer.Serialize(writer, obj);
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }

            Message replyMessage = Message.CreateMessage(messageVersion, action, new RawBodyWriter(body));

            replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            var respProp = new HttpResponseMessageProperty();

            respProp.Headers[HttpResponseHeader.ContentType] = "application/json";
            respProp.StatusCode = statusCode;
            replyMessage.Properties.Add(HttpResponseMessageProperty.Name, respProp);
            return(replyMessage);
        }
Esempio n. 19
0
        /// <summary/>
        private static void                     WriteRow(IRow row, JsonTextWriter writer)
        {
            // Row
            //  => { c1:v1, c2:v2, ...}

            // Header
            writer.WriteStartObject();

            // Fields
            var columns = row.Schema;
            for(int i=0; i<columns.Count; i++)
            {
                // Note: We simply delegate to Json.Net for all data conversions
                //  For data conversions beyond what Json.Net supports, do an explicit projection:
                //      ie: SELECT datetime.ToString(...) AS datetime, ...
                object value = row.Get<object>(i);

                // Note: We don't bloat the JSON with sparse (null) properties
                if(value != null)
                { 
                    writer.WritePropertyName(columns[i].Name, escape:true);
                    writer.WriteValue(value);
                }
            }

            // Footer
            writer.WriteEndObject();
        }
Esempio n. 20
0
        private static void RenderCacheFootprint(IEnumerable <ObjectCache> caches, HttpContext httpContext, ContentType outputType, bool expanded)
        {
            var response = httpContext.Response;

            switch (outputType)
            {
            case ContentType.Xml:
            {
                response.ContentEncoding = System.Text.Encoding.UTF8;
                response.Expires         = -1;
                var footprint = caches.First().GetCacheFootprintXml(expanded, httpContext.Request.Url);
                footprint.Save(response.Output);
            }
            break;

            case ContentType.Json:
            default:
                using (StreamWriter writer = new StreamWriter(response.OutputStream))
                {
                    var footprint = caches.First().GetCacheFootprintJson(expanded, httpContext.Request.Url);
                    using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(writer)
                    {
                        QuoteName = false, Formatting = Newtonsoft.Json.Formatting.Indented
                    })
                    {
                        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Serialize(jsonWriter, footprint);
                        jsonWriter.Flush();
                    }
                }
                break;
            }
        }
Esempio n. 21
0
        private JsonWriter CreateJsonWriter(TextWriter writer)
        {
            var jsonWriter = new JsonTextWriter(writer);
            jsonWriter.CloseOutput = false;

            return jsonWriter;
        }
        public void Add(IEnumerable <DocumentWithStream> documents)
        {
            if (Enabled == false)
            {
                return;
            }

            bool encrypt = Configuration.EncryptCacheItems;

            foreach (var document in documents)
            {
                string metaDataPath = Path.Combine(BaseCachePath, document.ID.ToString("D") + (encrypt ? ".e" : "") + ".meta");
                string contentPath  = Path.Combine(BaseCachePath, document.ID.ToString("D") + (encrypt ? ".e" : "") + ".data");

                using (var fileStream = File.OpenWrite(metaDataPath))
                    using (StreamWriter writer = encrypt ? new StreamWriter(CreateEncryptionStream(fileStream)) : new StreamWriter(fileStream))
                        using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
                        {
                            var serializer = new Newtonsoft.Json.JsonSerializer();
                            serializer.Serialize(json, document.Document);
                            json.Flush();
                        }

                using (var fileStream = new FileStream(contentPath, FileMode.Create, FileAccess.Write))
                    using (Stream stream = encrypt ? (Stream)CreateEncryptionStream(fileStream) : fileStream)
                    {
                        document.Stream.CopyTo(stream);
                        stream.Flush();
                        document.Stream.Flush();
                    }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// 数据集(DataSet)转DataJSON  一般用于显示查询结果。
        /// </summary>
        public static String dataTableToDataJson(DataTable dt,int pCount)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.Indented;
                jsonWriter.WriteStartArray();

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    jsonWriter.WriteStartObject();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        jsonWriter.WritePropertyName(dc.ColumnName);
                        jsonWriter.WriteValue(dt.Rows[i][dc.ColumnName]);
                    }
                    jsonWriter.WriteEndObject();
                }
                jsonWriter.WriteEndArray();

            }
            string hand = "{\"totalProperty\": " + pCount.ToString() + " , \"root\": ";
            return Convert.ToString(hand + sb + "}");
        }
Esempio n. 24
0
            public static void getFieldJsonStringArray(JsonTextWriter json, List<field> Fields)
            {
                json.WriteStartArray();

                foreach (field field in Fields)
                {

                    json.WriteStartObject();

                    json.WritePropertyName("field");
                    json.WriteValue(field.name.Trim());

                    json.WritePropertyName(TrimValue(field.name));
                    json.WriteValue(TrimValue(field.display));

                    json.WritePropertyName("type");
                    json.WriteValue(field.type.ToString());

                    json.WritePropertyName("display");
                    json.WriteValue(TrimValue(field.display));

                    json.WritePropertyName("ForView");
                    json.WriteValue(field.ForView);

                    json.WritePropertyName("ForUpdate");
                    json.WriteValue(field.ForUpdate);

                    json.WriteEndObject();
                }

                json.WriteEndArray();
            }
Esempio n. 25
0
        public void Compile()
        {
            System.Diagnostics.Debug.Assert(_inputs != null);
            if(!string.IsNullOrWhiteSpace(_query))
            {
                return;
            }

            var sb = new StringBuilder();

            using(var sw = new StringWriter(sb))
            using(JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.WriteStartObject();

                if(_inputs != null)
                {
                    _inputs.WriteJson(writer);
                }

                writer.WritePropertyName("query");

                writer.WriteStartArray();
                _phases.ForEach(p => writer.WriteRawValue(p.ToJsonString()));
                writer.WriteEndArray();

                writer.WriteEndObject();
            }

            _query = sb.ToString();
        }
Esempio n. 26
0
        /// <summary>
        /// Convert parameter list to json object
        /// </summary>
        public static string parameterFieldMapJson(parameters parms, string ProjectID, string QueryID)
        {
            StringWriter sw = new StringWriter();
            JsonTextWriter json = new JsonTextWriter(sw);

            json.WriteStartObject();
            json.WritePropertyName("results");
            json.WriteStartArray();
            json.WriteStartObject();
            // ProjectID and QueryID
            json.WritePropertyName("ProjectID");
            json.WriteValue(ProjectID);
            json.WritePropertyName("QueryID");
            json.WriteValue(QueryID);

            json.WritePropertyName("parameters");
            json.WriteRawValue(JsonConvert.SerializeObject(parms));

            json.WriteEndObject();
            json.WriteEndArray();
            json.WriteEndObject();

            json.Flush();
            sw.Flush();

            return sw.ToString();
        }
Esempio n. 27
0
		//JsonWriter writer = new JsonTextWriter();
		protected static string BasicRequest(int requestID, string method, string sessionID, params string[] parameters)
		{
			StringBuilder sb = new StringBuilder();
			StringWriter sw = new StringWriter(sb);

			using (JsonWriter writer = new JsonTextWriter(sw))
			{
				writer.Formatting = Formatting.Indented;

				writer.WriteStartObject();
				writer.WritePropertyName("jsonrpc");
				writer.WriteValue("2.0");
				writer.WritePropertyName("id");
				writer.WriteValue(requestID);
				writer.WritePropertyName("method");
				writer.WriteValue(method);
				writer.WritePropertyName("params");
				writer.WriteStartArray();
				writer.WriteValue(sessionID);
				foreach (var p in parameters)
					writer.WriteValue(p);
				writer.WriteEndArray();
				writer.WriteEndObject();
                return sb.ToString();
				//return sb.ToString().Replace("\n","");
			}
		}
Esempio n. 28
0
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            var serializer = new JsonSerializer
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                ContractResolver      = new NHibernateContractResolver()
            };
            StringWriter stringWriter = new StringWriter();
            StreamWriter streamWriter = new StreamWriter(response.OutputStream);
            JsonWriter   jsonWriter   = new Newtonsoft.Json.JsonTextWriter(stringWriter);

            serializer.Serialize(jsonWriter, Data);
            response.Write(stringWriter.ToString());
            //streamWriter.Write(stringWriter.ToString());
        }
Esempio n. 29
0
        public override bool Execute()
        {
            if (Items.Length == 0)
                throw new ArgumentException("The provided items contained zero entries.");

            if (!Directory.Exists(Path.GetDirectoryName(JsonFileName)))
                Directory.CreateDirectory(Path.GetDirectoryName(JsonFileName));

            JsonSerializer jsonSerializer = new JsonSerializer();
            using (StreamWriter streamWriter = new StreamWriter(JsonFileName))
            {
                using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                {
                    jsonWriter.Formatting = Formatting.Indented;

                    if (Items.Length > 1)
                        jsonWriter.WriteStartArray();

                    foreach (ITaskItem item in Items)
                    {
                        var customMd = item.CloneCustomMetadata();
                        jsonWriter.WriteStartObject();
                        foreach (var key in customMd.Keys)
                        {
                            var mdString = key.ToString();
                            var mdValue = customMd[key].ToString();

                            jsonWriter.WritePropertyName(mdString);

                            // if the value is surrounded in square brackets it's meant to be an array.
                            // split the value into its respective chunks and write it into a JSON array.
                            if (mdValue.Length > 0 && mdValue[0] == '[' && mdValue[mdValue.Length - 1] == ']')
                            {
                                mdValue = mdValue.Substring(1, mdValue.Length - 2);
                                jsonWriter.WriteStartArray();

                                var parts = mdValue.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var part in parts)
                                    jsonWriter.WriteValue(part);

                                jsonWriter.WriteEndArray();
                            }
                            else
                            {
                                jsonWriter.WriteValue(mdValue);
                            }
                        }

                        jsonWriter.WriteEndObject();
                    }

                    if (Items.Length > 1)
                        jsonWriter.WriteEndArray();

                    Log.LogMessage(MessageImportance.High, "Writing {0}.", JsonFileName);
                }
            }

            return true;
        }
Esempio n. 30
0
        /// <summary>
        /// Нажатие по кнопке "Сохранить файл"
        /// </summary>
        private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer();

            serializer.NullValueHandling = NullValueHandling.Ignore;
            serializer.TypeNameHandling  = TypeNameHandling.Auto;
            serializer.Formatting        = Formatting.Indented;

            var saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Figure | *.figure";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            var fileName = saveFileDialog.FileName;

            using (StreamWriter streamwriter = new StreamWriter(fileName))
            {
                using (Newtonsoft.Json.JsonWriter jWriter = new Newtonsoft.Json.JsonTextWriter(streamwriter))
                {
                    serializer.Serialize(jWriter, ListFigures.list);
                }
            }
        }
Esempio n. 31
0
        public static void Serialize(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath, Stream targetStream)
        {
            var json = JObject.FromObject(new
            {
                version = "2.0.0",
                songSourcePath,
                songs = songs.Select(song => new
                {
                    album = song.Album,
                    artist = song.Artist,
                    duration = song.Duration.Ticks,
                    genre = song.Genre,
                    path = song.OriginalPath,
                    title = song.Title,
                    trackNumber = song.TrackNumber,
                    artworkKey = song.ArtworkKey
                }),
                playlists = playlists.Select(playlist => new
                {
                    name = playlist.Name,
                    entries = playlist.Select(entry => SerializeSong(entry.Song))
                })
            }, new JsonSerializer { NullValueHandling = NullValueHandling.Ignore });

            using (var sw = new StreamWriter(targetStream, Encoding.UTF8, 64 * 1024, true))
            using (var jw = new JsonTextWriter(sw))
            {
                jw.Formatting = Formatting.Indented;

                json.WriteTo(jw);
            }
        }
Esempio n. 32
0
        public static void SaveToFile()
        {
            try
            {

                JsonSerializer serializer = new JsonSerializer();
                var prices = dataAccess.GetAllPrices();
                var sales = dataAccess.GetAllSales();
                var priceChanges = dataAccess.GetPriceChanges();

                string path = DataDir + "\\Prices.json";
                var writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, prices);
                writer.Close();

                path = DataDir + "\\Sales.json";
                writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, sales);
                writer.Close();

                path = DataDir + "\\priceChanges.json ";
                writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, priceChanges);
                writer.Close();

            }
            catch (Exception iException)
            {
                int x = 10;
                throw;
            }
        }
        public override void ExecuteResult(ControllerContext context)
        {
            JsonSerializer json = new JsonSerializer();

            json.NullValueHandling = NullValueHandling.Ignore;

            json.ObjectCreationHandling = ObjectCreationHandling.Replace;
            json.MissingMemberHandling = MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            String output = String.Empty;

            StringWriter sw = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);

            writer.Formatting = Formatting.Indented;

            writer.QuoteChar = '"';
            json.Serialize(writer, this.Data);

            output = sw.ToString();
            writer.Close();
            sw.Close();

            context.HttpContext.Response.ContentType = "application/json";
            context.HttpContext.Response.Write(output);
        }
Esempio n. 34
0
        public void Should_work_same_way_as_memory_stream_on_read()
        {
            var serializer = new JsonSerializer();

            var origin = new TestClass
            {
                Name = "FFasdf fasd  FASDfas   fadsfa  dafsdf  asdf a fsd ",
                CreatedAt = DateTime.Now,
                IsObsolete = true,
                Count = 31241325351
            };
            using (var writer = new JsonTextWriter(new StreamWriter(_ethalonStream)))
            {
                serializer.Serialize(writer, origin);
            }

            _testStream.ChangeBuffer(_ethalonBuffer);

            using (var reader = new JsonTextReader(new StreamReader(_testStream)))
            {
                var reburnished = serializer.Deserialize<TestClass>(reader);

                Assert.That(reburnished.Name, Is.EqualTo(origin.Name));
                Assert.That(reburnished.CreatedAt, Is.EqualTo(origin.CreatedAt));
                Assert.That(reburnished.IsObsolete, Is.EqualTo(origin.IsObsolete));
                Assert.That(reburnished.Count, Is.EqualTo(origin.Count));
            }
        }
Esempio n. 35
0
    //Serializar para obter lista de objetos
    private string Serialize(object value)
    {
        Type type = value.GetType();

        Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
        if (type == typeof(DataTable))
        {
            json.Converters.Add(new DataTableConverter());
        }
        if (type == typeof(DataSet))
        {
            json.Converters.Add(new DataSetConverter());
        }
        StringWriter sw = new StringWriter();

        Newtonsoft.Json.JsonTextWriter write = new Newtonsoft.Json.JsonTextWriter(sw);
        write.Formatting = Formatting.None;
        write.QuoteChar  = '"';
        json.Serialize(write, value);
        string output = sw.ToString();

        write.Close();
        sw.Close();
        return(output);
    }
    public void ValueFormatting()
    {
      StringBuilder sb = new StringBuilder();
      StringWriter sw = new StringWriter(sb);

      using (JsonWriter jsonWriter = new JsonTextWriter(sw))
      {
        jsonWriter.WriteStartArray();
        jsonWriter.WriteValue('@');
        jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
        jsonWriter.WriteValue(true);
        jsonWriter.WriteValue(10);
        jsonWriter.WriteValue(10.99);
        jsonWriter.WriteValue(0.99);
        jsonWriter.WriteValue(0.000000000000000001d);
        jsonWriter.WriteValue(0.000000000000000001m);
        jsonWriter.WriteValue((string)null);
        jsonWriter.WriteValue((object)null);
        jsonWriter.WriteValue("This is a string.");
        jsonWriter.WriteNull();
        jsonWriter.WriteUndefined();
        jsonWriter.WriteEndArray();
      }

      string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]";
      string result = sb.ToString();

      Console.WriteLine("ValueFormatting");
      Console.WriteLine(result);

      Assert.AreEqual(expected, result);
    }
Esempio n. 37
0
        public void ProcessRequest(HttpContext context)
        {
            if (!context.User.Identity.IsAuthenticated)
            {
                context.Response.StatusCode = 401;
                return;
            }

            int currentUserID = int.Parse(context.User.Identity.Name);

            context.Response.ContentType = "application/json";

            JsonSerializer serializer = JsonSerializer.Create();
            List<DTO> results = null;

            string query = context.Request.QueryString["query"];

            if (string.IsNullOrWhiteSpace(query))
            {
                results = GetMostRecent(currentUserID);
            }
            else
            {
                results = GetBySearch(currentUserID, query);
            }

            using (JsonWriter writer = new JsonTextWriter(context.Response.Output))
            {
                serializer.Serialize(writer, results);
            }
        }
        /// <summary>
        /// Writes the messages section of a protocol definition
        /// </summary>
        /// <param name="writer">writer</param>
        /// <param name="names">list of names written</param>
        /// <param name="encspace">enclosing namespace</param>
        internal void writeJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
        {
            writer.WriteStartObject();
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

            if (null != this.Request)
            {
                this.Request.WriteJsonFields(writer, names, null);
            }

            if (null != this.Response)
            {
                writer.WritePropertyName("response");
                Response.WriteJson(writer, names, encspace);
            }

            if (null != this.Error)
            {
                writer.WritePropertyName("errors");
                this.Error.WriteJson(writer, names, encspace);
            }

            if (null != Oneway)
            {
                writer.WritePropertyName("one-way");
                writer.WriteValue(Oneway);
            }

            writer.WriteEndObject();
        }
Esempio n. 39
0
 public static ObservableCollection<MediaFile> GetMedia()
 {
     if (File.Exists(libraryCachePath))
     {
         using (var file = File.OpenRead(libraryCachePath))
         using (var sr = new StreamReader(file))
         using (var jtr = new JsonTextReader(sr))
         {
             return new ObservableCollection<MediaFile>(serializer.Deserialize<List<MediaFile>>(jtr));
         }
     }
     else
     {
         var library = RefreshLibrary();
         if (!Directory.Exists(Path.GetDirectoryName(libraryCachePath)))
         {
             Directory.CreateDirectory(Path.GetDirectoryName(libraryCachePath));
         }
         using (var file = File.Open(libraryCachePath, FileMode.Create))
         using (var sw = new StreamWriter(file))
         using (var jtr = new JsonTextWriter(sw))
         {
             serializer.Serialize(jtr, library);
         }
         return new ObservableCollection<MediaFile>(library);
     }
 }
Esempio n. 40
0
        public static void SerializeMedicaments(IPharmacyContext context)
        {
            var productsReports =
                from medicament in context.Medicaments
                join sale in context.Sales on medicament.MedicamentId equals sale.MedicamentId
                select new
                {
                    MedicamentId = medicament.MedicamentId,
                    MedicamentName = medicament.Name,
                    ManufacturerName = medicament.Manufacturer.Name,
                    Quantity = sale.Quantity,
                    Income = sale.Quantity * sale.UnitPrice
                };

            JsonSerializer serializer = new JsonSerializer();

            foreach (var sale in productsReports)
            {
                var currentSaleFile = "../../../Reports/JsonReports/" + sale.MedicamentId + ".json";

                using (var fileStream = new FileStream(currentSaleFile, FileMode.Create))
                using (var streamWriter = new StreamWriter(fileStream))
                using (var jsonWriter = new JsonTextWriter(streamWriter))
                {
                    jsonWriter.Formatting = Formatting.Indented;

                    serializer.Serialize(jsonWriter, sale);
                }
            }
        }
Esempio n. 41
0
        public static Message SerializeMessage(JObject json, Message previousMessage)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms))
                {
                    using (JsonTextWriter jtw = new JsonTextWriter(sw))
                    {
                        json.WriteTo(jtw);
                        jtw.Flush();
                        sw.Flush();
                        Message result = Message.CreateMessage(MessageVersion.None, null, new RawBodyWriter(ms.ToArray()));
                        if (previousMessage != null)
                        {
                            result.Properties.CopyProperties(previousMessage.Properties);
                            result.Headers.CopyHeadersFrom(previousMessage.Headers);
                            previousMessage.Close();
                        }

                        result.Properties[JsonRpcConstants.JObjectMessageProperty] = json;
                        return result;
                    }
                }
            }
        }
Esempio n. 42
0
        public void Invoke(Session _Session, IncomingPacket _Packet)
        {
            string _ctmp = _Packet.GetString();

            string msj_f = HttpUtility.HtmlEncode(_ctmp.Replace("\\\"", "\""));

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.None;
                writer.WriteStartArray();
                writer.WriteValue((int)ServerOpcode.chat);
                writer.WriteValue(msj_f);
                writer.WriteValue(_Session.User.Name);

                if (_Session.User.rank >= 24)
                    writer.WriteValue(ChatType.CHAT_TYPE_GM); //type
                else
                    writer.WriteValue(0); //type

                if (_Session.User.guild > 0)
                    writer.WriteValue(_Session.User.guild_name);

                writer.WriteEndArray();
            }

            _Session.Broadcast(sb.ToString());
        }
Esempio n. 43
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            if (this.Data == null)
                return;

            var response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;

            var serializer = JsonSerializer.Create(this.Settings);
            using (var writer = new JsonTextWriter(response.Output))
            {
                serializer.Serialize(writer, Data);
                writer.Flush();
            }
        }
Esempio n. 44
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)

                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = !string.IsNullOrEmpty(ContentType)

              ? ContentType

              : "application/json";

            if (ContentEncoding != null)

                response.ContentEncoding = ContentEncoding;

            if (Data != null)
            {

                JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };

                JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);

                serializer.Serialize(writer, Data);

                writer.Flush();

            }
        }
Esempio n. 45
0
        public static async Task UpdateMdAddins(string commitOrBranch, string mdAddinsPath)
        {
            var status = await GetStatuses(commitOrBranch);

            var artifactsUri    = status.statuses.FirstOrDefault(s => s.context == "artifacts.json")?.target_url;
            var commit          = status.sha;
            var artifactsStream = await client.GetStreamAsync(artifactsUri);

            var artifact = (await JsonSerializer.DeserializeAsync <Artifacts[]>(artifactsStream))[0];

            Console.WriteLine($"commit = {commit}");

            var mono = new MonoExternal()
            {
                url       = artifact.url,
                version   = artifact.version,
                productId = artifact.productId,
                commit    = commit,
                releaseId = artifact.releaseId,
                sha256    = artifact.sha256,
                md5       = artifact.md5,
                size      = artifact.size
            };

            var outputStream = new MemoryStream();

            if (mdAddinsPath != null)
            {
                await UpdateDependencies(File.OpenRead(Path.Combine(mdAddinsPath, "bot-provisioning", "dependencies.csx")), outputStream, artifact);

                outputStream.Seek(0, SeekOrigin.Begin);
                //Console.Write (reader.ReadToEnd());
                using (var deps = File.Create(Path.Combine(mdAddinsPath, "bot-provisioning", "dependencies.csx"))) {
                    await outputStream.CopyToAsync(deps);
                }
                using (var external = File.Create(Path.Combine(mdAddinsPath, "external-components", "mono.json"))) {
                    //await JsonSerializer.SerializeAsync (external, mono, new JsonSerializerOptions () { WriteIndented = true });
                    using (var sw = new StreamWriter(external))
                        using (var jtw = new Whomp.JsonTextWriter(sw)
                        {
                            Formatting = Whomp.Formatting.Indented,
                            Indentation = 4,
                            IndentChar = ' '
                        })
                            (new Whomp.JsonSerializer()).Serialize(jtw, mono);
                }
            }
            else
            {
                Console.WriteLine(JsonSerializer.Serialize(mono, new JsonSerializerOptions()
                {
                    WriteIndented = true
                }));
                outputStream.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(outputStream);
                Console.Write(reader.ReadToEnd());
            }
        }
Esempio n. 46
0
 public string Serialize(object value, Type objectType)
 {
     using (var writer = new StringWriter())
         using (var jsonWriter = new NewtonsoftJson.JsonTextWriter(writer))
         {
             internalSerializer.Serialize(jsonWriter, value, objectType);
             return(writer.ToString());
         }
 }
Esempio n. 47
0
 /// <summary>
 /// Writes union schema in JSON format
 /// </summary>
 /// <param name="writer">JSON writer</param>
 /// <param name="names">list of named schemas already written</param>
 /// <param name="encspace">enclosing namespace of the schema</param>
 protected internal override void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
 {
     writer.WriteStartArray();
     foreach (Schema schema in this.Schemas)
     {
         schema.WriteJson(writer, names, encspace);
     }
     writer.WriteEndArray();
 }
Esempio n. 48
0
 private void CreateJsonWriter(TextWriter writer)
 {
     _textWriter             = new Newtonsoft.Json.JsonTextWriter(writer);
     _textWriter.IndentChar  = _indentChar;
     _textWriter.Indentation = _indentation;
     _textWriter.QuoteChar   = _quoteChar;
     _textWriter.Formatting  = _formatting == Formatting.Indented
         ? Newtonsoft.Json.Formatting.Indented
         : Newtonsoft.Json.Formatting.None;
 }
Esempio n. 49
0
        /// <summary>
        /// Returns the canonical JSON representation of this schema.
        /// </summary>
        /// <returns>The canonical JSON representation of this schema.</returns>
        public override string ToString()
        {
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
                using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    WriteJson(writer, new SchemaNames(), null); // stand alone schema, so no enclosing name space

                    return(sw.ToString());
                }
        }
        public static NewtonsoftToCosmosDBWriter CreateTextWriter()
        {
            StringWriter stringWriter = new StringWriter();

            Newtonsoft.Json.JsonTextWriter newtonsoftJsonWriter       = new Newtonsoft.Json.JsonTextWriter(stringWriter);
            NewtonsoftToCosmosDBWriter     newtonsoftToCosmosDBWriter = new NewtonsoftToCosmosDBWriter(
                newtonsoftJsonWriter,
                () => Encoding.UTF8.GetBytes(stringWriter.ToString()));

            return(newtonsoftToCosmosDBWriter);
        }
        public static string Serializar(object objetoParaSerializar)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new ContratoLogJson()
            };
            StringWriter stringWriter = new StringWriter();
            JsonWriter   jsonWriter   = new Newtonsoft.Json.JsonTextWriter(stringWriter);

            serializer.Serialize(jsonWriter, objetoParaSerializar);
            string serializedObject = stringWriter.ToString();

            return(serializedObject);
        }
        public static string ToJson <T>(this IEnumerable <T> toSerialize)
        {
            var serializer = new JsonSerializer
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                ContractResolver      = new NHibernateContractResolver()
            };
            StringWriter stringWriter = new StringWriter();
            JsonWriter   jsonWriter   = new Newtonsoft.Json.JsonTextWriter(stringWriter);

            serializer.Serialize(jsonWriter, toSerialize);
            return(stringWriter.ToString());
        }
Esempio n. 53
0
 /// <summary>
 /// метод сохранения класса организации
 /// </summary>
 public void SaveJson()
 {
     Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
     serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
     serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
     serializer.TypeNameHandling  = Newtonsoft.Json.TypeNameHandling.Auto;
     serializer.Formatting        = Newtonsoft.Json.Formatting.Indented;
     using (StreamWriter sw = new StreamWriter("Organization.json"))
         using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
         {
             serializer.Serialize(writer, organization, typeof(Organization));
         }
 }
Esempio n. 54
0
 public static string JsonPrettify(string json)
 {
     using (var stringReader = new StringReader(json))
         using (var stringWriter = new StringWriter())
         {
             var jsonReader = new Newtonsoft.Json.JsonTextReader(stringReader);
             var jsonWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter)
             {
                 Formatting = Newtonsoft.Json.Formatting.Indented
             };
             jsonWriter.WriteToken(jsonReader);
             return(stringWriter.ToString());
         }
 }
Esempio n. 55
0
    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public String SerializePerson()
    {
        PersonContainer pc = new PersonContainer(this);

        StringBuilder sb = new StringBuilder();
        StringWriter  sw = new StringWriter(sb);

        Newtonsoft.Json.JsonSerializer serializer1 = new Newtonsoft.Json.JsonSerializer();
        Newtonsoft.Json.JsonTextWriter jwriter     = new Newtonsoft.Json.JsonTextWriter(sw);

        serializer1.Serialize(jwriter, pc);

        return(sb.ToString());
    }
Esempio n. 56
0
        /// <summary>
        /// Serializes an object to an XML string. Unlike the other SerializeObject overloads
        /// this methods *returns a string* rather than a bool result!
        /// </summary>
        /// <param name="value">Value to serialize</param>
        /// <param name="throwExceptions">Determines if a failure throws or returns null</param>
        /// <returns>
        /// null on error otherwise the Xml String.
        /// </returns>
        /// <remarks>
        /// If null is passed in null is also returned so you might want
        /// to check for null before calling this method.
        /// </remarks>
        public static string Serialize(object value, bool throwExceptions = false, bool formatJsonOutput = false)
        {
            string  jsonResult = null;
            Type    type       = value.GetType();
            dynamic writer     = null;

            try
            {
                var json = new JsonSerializer();


                StringWriter sw = new StringWriter();

                writer = new Newtonsoft.Json.JsonTextWriter(sw);

                if (formatJsonOutput)
                {
                    writer.Formatting = Formatting.Indented;
                }
                else
                {
                    writer.Formatting = Formatting.None;
                }

                writer.QuoteChar = '"';
                json.Serialize(writer, value);

                jsonResult = sw.ToString();
                writer.Close();
            }
            catch (Exception ex)
            {
                if (throwExceptions)
                {
                    throw ex;
                }

                jsonResult = null;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }

            return(jsonResult);
        }
Esempio n. 57
0
        public static string gerarJSON(Object objeto)
        {
            var serializer = new JsonSerializer
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                ContractResolver      = new NHibernateContractResolver()
            };
            StringWriter stringWriter = new StringWriter();
            JsonWriter   jsonWriter   = new Newtonsoft.Json.JsonTextWriter(stringWriter);

            serializer.Serialize(jsonWriter, objeto);
            string serializedObject = stringWriter.ToString();

            return(JsonConvert.SerializeObject(objeto));
        }
Esempio n. 58
0
        public static void Save(string path, Company company)
        {
            JsonSerializer serializer = new JsonSerializer();

            serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
            serializer.NullValueHandling = NullValueHandling.Ignore;
            serializer.TypeNameHandling  = TypeNameHandling.Auto;
            serializer.Formatting        = Formatting.Indented;

            using (StreamWriter sw = new StreamWriter(path))
                using (JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, company, typeof(Company));
                }
        }
Esempio n. 59
0
        /// <summary>
        /// Returns the canonical JSON representation of this schema.
        /// </summary>
        /// <returns>The canonical JSON representation of this schema.</returns>
        public override string ToString()
        {
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
                using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName("type");

                    WriteJson(writer, new SchemaNames(), null); // stand alone schema, so no enclosing name space

                    writer.WriteEndObject();

                    return(sw.ToString());
                }
        }
Esempio n. 60
-1
        public static void Notice(UserManager.UserClass _user)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.None;
                writer.WriteStartArray();
                writer.WriteValue((int)ServerOpcode.room_state);

                writer.WriteStartArray();

                writer.WriteStartArray();
                writer.WriteValue("GameServerDB");
                writer.WriteValue("");
                writer.WriteValue(9);
                writer.WriteEndArray();

                writer.WriteStartArray();
                writer.WriteValue("Bienvenido!");
                writer.WriteValue("");
                writer.WriteValue(9);
                writer.WriteEndArray();

                writer.WriteEndArray();

                writer.WriteEndArray();
            }
            _user.sep.Send(sb.ToString());
        }