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(); } }
private static string toJSON(SqlDataReader rdr) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonWriter jsonWriter = new JsonTextWriter(sw); jsonWriter.WriteStartArray(); while (rdr.Read()) { int fieldcount = rdr.FieldCount; // count how many columns are in the row object[] values = new object[fieldcount]; // storage for column values rdr.GetValues(values); // extract the values in each column jsonWriter.WriteStartObject(); for (int index = 0; index < fieldcount; index++) { string colName = rdr.GetName(index); object value = values[index]; jsonWriter.WritePropertyName(colName); if (value == DBNull.Value) value = ""; else if (colName.Contains("date") && !colName.Contains("by")) value = String.Format("{0:MM/dd/yyyy HH:mm tt}", value); jsonWriter.WriteValue(value); } jsonWriter.WriteEndObject(); } jsonWriter.WriteEndArray(); return sb.ToString(); }
/// <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(); }
public string Serialize() { var sb = new StringBuilder(); var sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("public"); jsonWriter.WriteValue(true); jsonWriter.WritePropertyName("files"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName(File); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("content"); jsonWriter.WriteValue(Code); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); } return sb.ToString(); }
public static void WriteAsJson([NotNull] this LayoutBuilder layoutBuilder, [NotNull] TextWriter writer) { var output = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; output.WriteStartObject("Layout"); output.WriteStartArray("Devices"); foreach (var deviceBuilder in layoutBuilder.Devices) { output.WriteStartObject(); output.WritePropertyStringIf("Name", deviceBuilder.DeviceName); output.WritePropertyStringIf("Layout", deviceBuilder.LayoutItemPath); output.WriteStartArray("Renderings"); foreach (var renderingBuilder in deviceBuilder.Renderings.Where(r => r.ParentRendering == null)) { WriteAsJson(output, deviceBuilder, renderingBuilder); } output.WriteEndArray(); output.WriteEndObject(); } output.WriteEndArray(); output.WriteEndObject(); }
/// <summary> /// Serializes <see cref="Graphic"/> into JSON string. /// </summary> /// <param name="graphic">graphic to serialize into JSON.</param> /// <returns>string representation of the JSON object.</returns> public static string ToJson(this Graphic graphic) { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (JsonWriter jw = new JsonTextWriter(sw)) { if (graphic.Geometry != null) { jw.WriteStartObject(); jw.WritePropertyName("geometry"); // Gets the JSON string representation of the Geometry. jw.WriteRawValue(graphic.Geometry.ToJson()); jw.WriteEndObject(); } if (graphic.Attributes.Count > 0) { jw.WriteStartObject(); foreach (var item in graphic.Attributes) { jw.WritePropertyName(item.Key); jw.WriteValue(item.Value); } jw.WriteEndObject(); } } return sb.ToString(); } }
public String ToJSONRepresentation() { StringBuilder sb = new StringBuilder(); JsonWriter jw = new JsonTextWriter(new StringWriter(sb)); jw.Formatting = Formatting.Indented; jw.WriteStartObject(); jw.WritePropertyName(this._description); jw.WriteStartArray(); foreach(MailStructure mail in this._mailStructures) { jw.WriteStartObject(); jw.WritePropertyName("Id"); jw.WriteValue(mail.Id); jw.WritePropertyName("Uuid"); jw.WriteValue(mail.Uuid); jw.WritePropertyName("MailDate"); jw.WriteValue(mail.MailDate); jw.WritePropertyName("From"); jw.WriteValue(mail.From); jw.WritePropertyName("Subject"); jw.WriteValue(mail.Subject); jw.WritePropertyName("Body"); jw.WriteValue(mail.Body); jw.WritePropertyName("AttachmentExist"); jw.WriteValue((mail.AttachmentExist ? "1" : "0")); jw.WritePropertyName("AttachmentFiles"); jw.WriteValue(mail.AttachmentFiles); jw.WriteEndObject(); } jw.WriteEndArray(); jw.WriteEndObject(); return sb.ToString(); }
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); }
/// <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(); }
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); }
/// <summary> /// Generate the json output for the page. /// </summary> /// <param name="page"> /// The page. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string GenerateJson(IContent page) { string json; List<KeyValuePair<string, string>> propertyValues = page.GetPropertyValues(); StringBuilder stringBuilder = new StringBuilder(); using (StringWriter sw = new StringWriter(stringBuilder, CultureInfo.InvariantCulture)) { JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName(page.Name); jsonWriter.WriteStartObject(); foreach (KeyValuePair<string, string> content in propertyValues) { jsonWriter.WritePropertyName(content.Key); jsonWriter.WriteValue(TextIndexer.StripHtml(content.Value, content.Value.Length)); } jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); json = sw.ToString(); } return json; }
public static string DataTableToJSON(DataTable dt, string dtName) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jw = new JsonTextWriter(sw)) { JsonSerializer ser = new JsonSerializer(); jw.WriteStartObject(); jw.WritePropertyName(dtName); jw.WriteStartArray(); foreach (DataRow dr in dt.Rows) { jw.WriteStartObject(); foreach (DataColumn dc in dt.Columns) { jw.WritePropertyName(dc.ColumnName); ser.Serialize(jw, dr[dc].ToString()); } jw.WriteEndObject(); } jw.WriteEndArray(); jw.WriteEndObject(); sw.Close(); jw.Close(); } return sb.ToString(); }
/// <summary> /// Serialize this phase to JSON. /// </summary> /// <returns>The phase as a JSON string.</returns> public string ToJsonString() { /* * NB: JsonTextWriter is guaranteed to close the StringWriter * https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonTextWriter.cs#L150-L160 */ var sb = new StringBuilder(); var sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.WriteStartObject(); writer.WritePropertyName(PhaseType); // phase start writer.WriteStartObject(); WriteJson(writer); writer.WriteProperty("keep", keep); writer.WriteEndObject(); // phase end writer.WriteEndObject(); } return sb.ToString(); }
public bool Start(string context) { this.context = context; string uri = baseURI + @"start/"; string method = "POST"; StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("context"); jsonWriter.WriteValue(this.context); jsonWriter.WritePropertyName("participants"); jsonWriter.WriteStartArray(); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("name"); // use the current window user jsonWriter.WriteValue(Environment.UserName); jsonWriter.WritePropertyName("id"); // use the computer name + windows user name jsonWriter.WriteValue(Environment.MachineName + "-" + Environment.UserName); jsonWriter.WriteEndObject(); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); } string json = sb.ToString(); HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.KeepAlive = false; req.Method = method; byte[] buffer = Encoding.ASCII.GetBytes(json); req.ContentLength = buffer.Length; req.ContentType = "application/json"; Stream PostData = req.GetRequestStream(); PostData.Write(buffer, 0, buffer.Length); PostData.Close(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; StreamReader tr = new StreamReader(resp.GetResponseStream()); json = tr.ReadToEnd(); Dictionary<string, string> respValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); if (respValues.ContainsKey("status") && respValues["status"] == "success") { this.dialogueID = respValues["dlg_id"]; this.IsRunning = true; return true; } return false; }
protected void Page_Load(object sender, EventArgs e) { Response.Clear(); var oSB = new StringBuilder(); var oSW = new StringWriter(oSB); using (JsonWriter oWriter = new JsonTextWriter(oSW)) { oWriter.Formatting = Formatting.Indented; oWriter.WriteStartObject(); if (IsAuthenticated && ApplicationContext.IsStaff) { oWriter.WritePropertyName("results"); oWriter.WriteStartArray(); if (!string.IsNullOrEmpty(Request.QueryString["q"])) { var sQuery = Request.QueryString["q"]; DataAccess.Log = new DebugTextWriter(); var oResults = DataAccess.fn_Producer_GetCustomerLookup(); oResults = oResults.Where(row => (row.FirstName + " " + row.LastName + " (" + row.Username + ")").Contains(sQuery)) .Distinct().Take(30); foreach (var oResult in oResults) { oWriter.WriteStartObject(); oWriter.WritePropertyName("id"); oWriter.WriteValue(oResult.MPUserID.ToString()); oWriter.WritePropertyName("name"); oWriter.WriteValue(string.Format("{0} {1} ({2})", oResult.FirstName, oResult.LastName, oResult.Username)); oWriter.WriteEndObject(); } oWriter.WriteEnd(); } } oWriter.WriteEndObject(); } Response.ContentType = "application/json"; Response.Write(oSB.ToString()); Response.End(); }
static void Main(string[] args) { // Set connection parameters var parameters = new RfcConfigParameters(); parameters[RfcConfigParameters.Client] = "050"; parameters[RfcConfigParameters.Language] = "DE"; parameters[RfcConfigParameters.User] = "SCHUENGE"; parameters[RfcConfigParameters.Password] = ""; parameters[RfcConfigParameters.MessageServerHost] = "sawitk80.ceu.heidelberg.com"; parameters[RfcConfigParameters.MessageServerService] = "3641"; parameters[RfcConfigParameters.Name] = "K80"; parameters[RfcConfigParameters.SystemID] = "K80"; parameters[RfcConfigParameters.LogonGroup] = "K80001"; // Get destination (i.e. connection to SAP ERP system) var destination = RfcDestinationManager.GetDestination(parameters); JsonWriter writer = new JsonTextWriter(new StreamWriter("test.json")); writer.Formatting = Formatting.Indented; writer.WriteStartObject(); var customerNumber = "0080300010"; ReadCustomerContacts(customerNumber, destination, writer); ReadCustomerEquipments(customerNumber, destination, writer); writer.WriteEndObject(); writer.Close(); }
private static void BuildObject(object obj, Stream stream, string contenttype, int apiVersion) { var type = obj.GetType(); var properties = type.GetProperties(); var attrs = System.Attribute.GetCustomAttributes(type); using (var streamWriter = new StreamWriter(stream)) { using (var writer = new JsonTextWriter(streamWriter)) { writer.WriteStartObject(); foreach (var property in properties) { var includeProperty = true; foreach (var attr in property.GetCustomAttributes(false)) { var attribute = attr as jcPVSAttribute; if (attribute != null && attribute?.GetMinAPIVersion() >= apiVersion) { includeProperty = false; continue; } } if (!includeProperty) { continue; } writer.WritePropertyName(property.Name); writer.WriteValue(property.GetValue(obj)); } writer.WriteEndObject(); } } }
public void Serialize(JsonWriter writer) { if (string.IsNullOrWhiteSpace(MimeType) || string.IsNullOrWhiteSpace(Content)) return; var sb = new StringBuilder(); var sw = new StringWriter(sb); using (JsonWriter jw = new JsonTextWriter(sw)) { jw.WritePropertyName(MimeType); jw.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Content)) { jw.WriteRawValue(Content); } jw.WriteEndObject(); if (jw.WriteState == WriteState.Error) sb.Clear(); } writer.WriteRawValue(sb.ToString()); }
internal string ToJson() { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (JsonWriter jw = new JsonTextWriter(sw)) { jw.WriteStartObject(); if (!string.IsNullOrEmpty(AreaType)) { jw.WritePropertyName("areaType"); jw.WriteValue(AreaType); } if (!string.IsNullOrEmpty(BufferUnits)) { jw.WritePropertyName("bufferUnits"); jw.WriteValue(BufferUnits); } if (BufferRadii != null && BufferRadii.Count > 0) { jw.WritePropertyName("Drives"); jw.WriteStartArray(); foreach (var radius in BufferRadii) jw.WriteValue(radius); jw.WriteEndArray(); } jw.WriteEndObject(); } } return sb.ToString(); }
/// <summary> /// 返回编辑用户信息的的json格式 /// </summary> /// <param name="user"></param> /// <returns></returns> public string EditUserInfoToJson(Web_User user) { StringBuilder Json = new StringBuilder(); StringWriter sw = new StringWriter(Json); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("LOGNAME"); jsonWriter.WriteValue(user.LOGNAME); jsonWriter.WritePropertyName("REALNAME"); jsonWriter.WriteValue(user.REALNAME); jsonWriter.WritePropertyName("USERGROUPID"); jsonWriter.WriteValue(user.GROUP.Group_ID); //jsonWriter.WritePropertyName("USERGROUP"); //jsonWriter.WriteValue(user.GROUP.USERGROUP); jsonWriter.WritePropertyName("STATE"); jsonWriter.WriteValue(user.STATE); jsonWriter.WritePropertyName("MEMO"); jsonWriter.WriteValue(user.MEMO); jsonWriter.WritePropertyName("id"); jsonWriter.WriteValue(user.ID); jsonWriter.WriteEndObject(); } return Json.ToString(); }
protected void btnSend_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonWriter jsonWriter = new JsonTextWriter(sw); jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("name"); jsonWriter.WriteValue(txtName.Text); jsonWriter.WritePropertyName("description"); jsonWriter.WriteValue(txtDesc.Text); jsonWriter.WritePropertyName("priority"); jsonWriter.WriteValue((dpdPri.Text).ToUpper()); jsonWriter.WriteEndObject(); string output = sw.ToString(); jsonWriter.Close(); sw.Close(); //string[] args = new string[3]; //args[0] = txtName.Text; //args[1] = txtDesc.Text; //args[2] = txtPri.Text; //string message = string.Join(" ", args); byte[] body = System.Text.Encoding.UTF8.GetBytes(output); producer.SendMessage(body); }
/// <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()); }
public void ProcessRequest(HttpContext context) { string reVal = string.Empty; context.Response.ContentType = "text/plain"; IEnumerable<ADM_USER> list = from m in etMgr.ADM_USER.OfType<ADM_USER>() select m; StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartArray(); foreach (ADM_USER m in list) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("name"); jsonWriter.WriteValue(string.IsNullOrEmpty(m.REAL_NAME) ? m.USERNAME : m.REAL_NAME); jsonWriter.WritePropertyName("id"); jsonWriter.WriteValue(m.USER_ID); jsonWriter.WriteEndObject(); } jsonWriter.WriteEnd(); } reVal = sb.ToString(); context.Response.Write(reVal); }
internal string ToJson() { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (JsonWriter jw = new JsonTextWriter(sw)) { jw.WriteStartObject(); if (GeometryType == ESRI.ArcGIS.Client.Tasks.GeometryType.Point || GeometryType == ESRI.ArcGIS.Client.Tasks.GeometryType.Polygon) { jw.WritePropertyName("geometryType"); jw.WriteValue(string.Format("esriGeometry{0}", GeometryType)); } jw.WritePropertyName("spatialRel"); jw.WriteValue(SpatialRelationship.ToString()); if (!string.IsNullOrEmpty(Where)) { jw.WritePropertyName("where"); jw.WriteValue(Where); } jw.WriteEndObject(); } } return sb.ToString(); }
public static void Emit(string msg, params object[] data) { if(outputFile != null) { outputFile.Write(DateTime.Now.ToString("o")); outputFile.Write(" " + msg + " "); try { JsonTextWriter json = new JsonTextWriter(outputFile); int ndata = data.Length / 2; json.WriteStartObject(); for(int k = 0; k < ndata; k++) { json.WritePropertyName((string) data[2 * k]); jsonSerializer.Serialize(json, data[2 * k + 1]); } json.WriteEndObject(); } catch(Exception e) { outputFile.WriteLine("...<" + e.ToString() + ">"); outputFile.Flush(); return; } outputFile.WriteLine(); outputFile.Flush(); } }
public void Save(JsonTextWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("regions"); writer.WriteStartArray(); foreach ( var region in Regions ) { writer.WriteStartObject(); writer.WritePropertyName("start"); writer.WriteValue(region.Item1); writer.WritePropertyName("length"); writer.WriteValue(region.Item2); writer.WriteEndObject(); } writer.WriteEndArray(); writer.WriteEndObject(); }
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(); }
/// <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 + "}"); }
//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",""); } }
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; }
/// <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(); }
//https://webServiceURL/version/devices/deviceLibraryIdentifier/registrations/passTypeIdentifier?passesUpdatedSince=tag public HttpResponseMessage Get(string version, string deviceLibraryIdentifier, string passTypeIdentifier, HttpRequestMessage request) { //List<string> updatedSerialNumbers = new List<string>(); //updatedSerialNumbers.Add("121212111"); //Dictionary<string, string> outputDictionary = new Dictionary<string, string>(); //outputDictionary.Add("lastUpdated", "21/07/2012"); //outputDictionary.Add("serialNumbers", JsonConvert.SerializeObject(updatedSerialNumbers)); var response = new HttpResponseMessage(HttpStatusCode.OK); //string json = JsonConvert.SerializeObject(outputDictionary); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName("lastUpdated"); writer.WriteValue("21/07/2012"); writer.WritePropertyName("serialNumbers"); writer.WriteStartArray(); writer.WriteValue("121212111"); writer.WriteEndArray(); writer.WriteEndObject(); } response.Content = new StringContent(sb.ToString(), Encoding.UTF8, "application/json"); return response; }
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(); }
internal static string JsonSerializePayload(IEnumerable<KeyValuePair<string, object>> payload) { try { using (var writer = new StringWriter(CultureInfo.InvariantCulture)) using (var jsonWriter = new JsonTextWriter(writer) { Formatting = Newtonsoft.Json.Formatting.Indented, CloseOutput = false }) { jsonWriter.WriteStartObject(); foreach (var item in payload) { JsonWriteProperty(jsonWriter, item.Key, item.Value); } jsonWriter.WriteEndObject(); jsonWriter.Flush(); return writer.ToString(); } } catch (JsonWriterException jwe) { SemanticLoggingEventSource.Log.EventEntrySerializePayloadFailed(jwe.ToString()); var errorDictionary = new Dictionary<string, object> { { "Error", string.Format(CultureInfo.CurrentCulture, Properties.Resources.JsonSerializationError, jwe.Message) } }; return JsonConvert.SerializeObject(errorDictionary, Newtonsoft.Json.Formatting.Indented); } }
static void Main(string[] args) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Newtonsoft.Json.Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName("CPU"); writer.WriteValue("Intel"); writer.WritePropertyName("PSU"); writer.WriteValue("500W"); writer.WritePropertyName("Drives"); writer.WriteStartArray(); writer.WriteValue("DVD read/writer"); writer.WriteComment("(broken)"); writer.WriteValue("500 gigabyte hard drive"); writer.WriteValue("200 gigabype hard drive"); writer.WriteEnd(); writer.WriteEndObject(); } File.WriteAllText(Environment.CurrentDirectory + "/rhcdata.json", sw.ToString()); Console.WriteLine(sw.ToString()); Console.ReadLine(); }
/// <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()); } }
/// <summary> /// Returns the canonical JSON representation of this schema. /// </summary> /// <returns>The canonical JSON representation of this schema.</returns> public override string ToString() { System.IO.StringWriter sw = new System.IO.StringWriter(); Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw); if (this is PrimitiveSchema || this is UnionSchema) { writer.WriteStartObject(); writer.WritePropertyName("type"); } WriteJson(writer, new SchemaNames(), null); // stand alone schema, so no enclosing name space if (this is PrimitiveSchema || this is UnionSchema) { writer.WriteEndObject(); } return(sw.ToString()); }
/// <summary> /// 泛型对象转换到JSON表示字符串 /// </summary> /// <param name="objectT">目标对象</param> /// <param name="totalResults">总记录数</param> /// <returns>返回JSON表示字符串</returns> public static string ToJSON(object objectT, int totalResults) { StringBuilder sbJSON; string rawJSON = JsonConvert.SerializeObject(objectT); StringWriter sw = new StringWriter(); JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw); writer.WriteStartObject(); writer.WritePropertyName("TotalRecord"); //总记录数 writer.WriteValue(totalResults); writer.WritePropertyName("Data"); //数据集合 writer.WriteRaw(rawJSON); writer.WriteEndObject(); writer.Flush(); sbJSON = sw.GetStringBuilder(); return(sbJSON.ToString()); }
public void ExportProductsJson(string path, string storagePath, int workProcessID, bool zipIt = true) { try { bool cancelRequested; workProcessService.Update(workProcessID, "Export started", 0); var totalAll = db.Categories.Count() + db.Products.Count() + db.OptionCategories.Count() + db.Options.Count() + db.Uploads.Count(); var countAll = 0; var fileName = "Products_" + DateTime.Now.ToString("yyyyMMddTHHmmss"); var serializer = new JsonSerializer(); serializer.Converters.Add(new JavaScriptDateTimeConverter()); serializer.NullValueHandling = NullValueHandling.Ignore; serializer.Formatting = Formatting.Indented; serializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); using (var sw = new StreamWriter(Path.Combine(path, fileName + ".json"))) using (JsonWriter writer = new JsonTextWriter(sw)) { writer.WriteStartObject(); #region Write categories writer.WritePropertyName("categories"); writer.WriteStartArray(); var count = 0; var total = categoryService.FindAll().Count(); foreach (var category in categoryService.FindAll().OrderBy(c => c.Id).InChunksOf(100)) { serializer.Serialize(writer, new { category.Id, category.Name, category.ParentId, category.Description, category.IsVisible, SortOrder = category.SortOrder.AsNullIfDefault() }); count++; countAll++; if (count % 100 == 0) { workProcessService.Update(workProcessID, string.Format("Exporting product categories ({0} of {1})", count, total), ((double)countAll / totalAll) * 100.0, out cancelRequested); if (cancelRequested) { return; } } } writer.WriteEndArray(); #endregion #region Write option categories writer.WritePropertyName("optionCategories"); writer.WriteStartArray(); count = 0; total = db.OptionCategories.Count(); foreach (var category in db.OptionCategories.OrderBy(c => c.Id).InChunksOf(100)) { serializer.Serialize(writer, new { category.Id, category.Name, category.Description, category.Type, category.IncludeInFilters }); count++; countAll++; if (count % 100 == 0) { workProcessService.Update(workProcessID, string.Format("Exporting option categories ({0} of {1})", count, total), ((double)countAll / totalAll) * 100.0, out cancelRequested); if (cancelRequested) { return; } } } writer.WriteEndArray(); #endregion #region Write options writer.WritePropertyName("options"); writer.WriteStartArray(); count = 0; total = db.Options.Count(); foreach (var option in db.Options.OrderBy(o => o.Id).InChunksOf(100)) { serializer.Serialize(writer, new { option.Id, option.Name, option.OptionCategoryId, option.Description, }); count++; countAll++; if (count % 100 == 0) { workProcessService.Update(workProcessID, string.Format("Exporting options ({0} of {1})", count, total), ((double)countAll / totalAll) * 100.0, out cancelRequested); if (cancelRequested) { return; } } } writer.WriteEndArray(); #endregion #region Write products writer.WritePropertyName("products"); writer.WriteStartArray(); count = 0; total = productFinder.FindAll().Count(); foreach (var product in productFinder.FindAll().OrderBy(p => p.Id).InChunksOf(100)) { serializer.Serialize(writer, new { product.Id, product.Sku, product.Name, product.Price, product.CostPrice, product.RetailPrice, product.SalePrice, Weight = product.Weight.AsNullIfDefault(), product.Quantity, product.Description, product.Keywords, product.IsFeatured, product.IsVisible, Categories = product.Categories.Select(c => c.Id).ToArray(), TaxClass = product.TaxClass != null ? product.TaxClass.Name : null, Sections = product.Sections.Select(s => new { s.Title, s.Type, s.Position, s.Settings, s.Priority }).ToArray(), Options = product.Options.Select(o => o.Id).ToArray(), Uploads = product.Uploads.Select(u => new { u.Id, u.SortOrder, u.Type }).ToArray(), Skus = product.Skus.Select(s => new { s.Sku, s.UPC, s.Quantity, s.Price, s.Weight, Options = s.Options.Select(o => o.Id).ToArray(), Uploads = s.Uploads.Select(u => u.Id).ToArray() }) }); count++; countAll++; if (count % 100 == 0) { workProcessService.Update(workProcessID, string.Format("Exporting products ({0} of {1})", count, total), ((double)countAll / totalAll) * 100.0, out cancelRequested); if (cancelRequested) { return; } } } writer.WriteEndArray(); #endregion writer.WriteEndObject(); } if (zipIt) { using (var zip = new ZipFile(Path.Combine(path, fileName + ".zip"))) { zip.AddFile(Path.Combine(path, fileName + ".json"), "").FileName = "Export.json"; zip.Save(); foreach (var upload in db.Uploads.Where(u => u.Type == UploadType.ProductImage) .OrderBy(u => u.Id).InChunksOf(100)) { zip.AddFile(Path.Combine(storagePath, upload.Id.ToString()), "") .FileName = upload.Id + ".jpg"; } zip.SaveProgress += delegate(object sender, SaveProgressEventArgs args) { if (args.EntriesSaved == 0 || args.EntriesSaved % 100 != 0) { return; } workProcessService.Update(workProcessID, string.Format("Archiving photos ({0} of {1})", args.EntriesSaved, args.EntriesTotal), ((double)(countAll + args.EntriesSaved) / totalAll) * 100.0, out cancelRequested); if (cancelRequested) { args.Cancel = true; } }; zip.Save(); } File.Delete(Path.Combine(path, fileName + ".json")); } workProcessService.Update(workProcessID, "Export completed", 100, isComplete: true); } catch (Exception err) { try { workProcessService.Update(workProcessID, "Export failed", 100, isComplete: true, error: err.Message); } catch { // Probably db issue; do not throw exception to avoid thread kill } } }
private void Login() { //string username = ""; //if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"])) //{ // username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["username"])); //} //string pwd = ""; //if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"])) //{ // pwd = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["pwd"])); // //pwd = WebBasic.Encryption.Encrypt(pwd); // pwd = Utils.Encrypt(pwd); //} string username = ""; if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"])) { username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request.Form["username"])); } string pwd = ""; if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"])) { pwd = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request.Form["pwd"])); //pwd = WebBasic.Encryption.Encrypt(pwd); pwd = Utils.Encrypt(pwd); } int valid_type = 1;//1、根据用户名判断 2、根据邮箱判断 if (username.Contains("@")) { valid_type = 2; } int result = 0; if (userBll.SelectUsernameEmailExist(username) > 0) { int count = userBll.SelectUserPwdIsTrue(username, pwd, valid_type); if (count > 0) { result = UserLogin(username);//执行登录,并返回登录结果 } else { result = 2;//用户名或密码错误 } } else { result = 4;//用户名不存在 } StringWriter sw = new StringWriter(); Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw); writer.WriteStartObject(); writer.WritePropertyName("status"); writer.WriteValue("200"); writer.WritePropertyName("result"); writer.WriteValue(result.ToString()); writer.WriteEndObject(); writer.Flush(); string jsonText = sw.GetStringBuilder().ToString(); Response.Write(jsonText); }
/// <summary>写入对象结束标记。</summary> public void WriteEndObject() { _textWriter.WriteEndObject(); }
public override byte[] GenerateBody(SendDirectMessageOptions args) { using (var tw = new System.IO.StringWriter()) using (var writer = new Newtonsoft.Json.JsonTextWriter(tw)) { writer.WriteStartObject(); writer.WritePropertyName("event"); writer.WriteStartObject(); writer.WritePropertyName("type"); writer.WriteValue("message_create"); writer.WritePropertyName("message_create"); writer.WriteStartObject(); writer.WritePropertyName("target"); writer.WriteStartObject(); writer.WritePropertyName("recipient_id"); writer.WriteValue(args.Recipientid); writer.WriteEndObject(); writer.WritePropertyName("message_data"); writer.WriteStartObject(); writer.WritePropertyName("text"); writer.WriteValue(args.Text); if (args.Mediaid != null) { writer.WritePropertyName("attachment"); writer.WriteStartObject(); writer.WritePropertyName("type"); writer.WriteValue(args.Mediatype); writer.WritePropertyName("media"); writer.WriteStartObject(); writer.WritePropertyName("id"); writer.WriteValue(args.Mediaid); writer.WriteEndObject(); writer.WriteEndObject(); } if (args.Quickreplies?.Any() ?? false) { writer.WritePropertyName("quick_reply"); writer.WriteStartObject(); writer.WritePropertyName("type"); writer.WriteValue("options"); writer.WritePropertyName("options"); writer.WriteStartArray(); foreach (var qr in args.Quickreplies) { writer.WriteStartObject(); writer.WritePropertyName("label"); writer.WriteValue(qr.Label); writer.WritePropertyName("description"); writer.WriteValue(qr.Description); writer.WritePropertyName("metdata"); writer.WriteValue(qr.Metadata); writer.WriteEndObject(); } writer.WriteEndArray(); writer.WriteEndObject(); } writer.WriteEndObject(); writer.WriteEndObject(); writer.WriteEndObject(); writer.WriteEndObject(); return(System.Text.UTF8Encoding.UTF8.GetBytes(tw.ToString())); } }
private void LoginManage() { StringWriter sw = new StringWriter(); Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw); int code_result = ValidCheckCode();//检测验证码:1、成功 2、验证码错误 3、请更换验证码重试 if (code_result == 1) { string name = ""; if (!string.IsNullOrEmpty(HttpContext.Current.Request["name"])) { name = InText.SafeSql(HttpContext.Current.Request["name"]); } string pwd = ""; if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"])) { pwd = WebBasic.Encryption.Encrypt(InText.SafeSql(HttpContext.Current.Request["pwd"])); } String sql = string.Format("select * from t_admin where name='{0}' and pwd='{1}'", name, pwd); DataTable dt = artBll.SelectToDataTable(sql); if (dt.Rows.Count > 0) { //将后台人员信息保存至session Session["adminId"] = dt.Rows[0]["id"].ToString(); Session["login_name"] = dt.Rows[0]["name"].ToString(); Session["pwd"] = WebBasic.Encryption.Encrypt(dt.Rows[0]["pwd"].ToString()); //----将信息保存到Cookie---- HttpCookie hc = new HttpCookie("Cookie_admin"); hc.Values["adminId"] = HttpUtility.UrlEncode(dt.Rows[0]["id"].ToString()); hc.Values["login_name"] = HttpUtility.UrlEncode(dt.Rows[0]["name"].ToString()); hc.Values["pwd"] = WebBasic.Encryption.Encrypt(dt.Rows[0]["pwd"].ToString());//密码再次加密 if (cookie_domain != "") { hc.Domain = cookie_domain; } hc.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(hc); //writer.WriteStartArray(); writer.WriteStartObject(); writer.WritePropertyName("result"); writer.WriteValue("success"); writer.WriteEndObject(); writer.Flush(); //writer.WriteEndArray(); } else { //writer.WriteStartArray(); writer.WriteStartObject(); writer.WritePropertyName("result"); writer.WriteValue("failed"); writer.WritePropertyName("message"); writer.WriteValue("用户名或密码错误"); writer.WriteEndObject(); writer.Flush(); //writer.WriteEndArray(); } } else { //writer.WriteStartArray(); writer.WriteStartObject(); writer.WritePropertyName("result"); writer.WriteValue("failed"); writer.WritePropertyName("message"); if (code_result == 2) { writer.WriteValue("验证码错误"); } else { writer.WriteValue("请更换验证码重试"); } writer.WriteEndObject(); writer.Flush(); //writer.WriteEndArray(); } string jsonText = sw.GetStringBuilder().ToString(); //jsonText = "{\"returnValue\":" + jsonText + "}"; Response.Write(jsonText); }
private void register() { string username = ""; if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"])) { username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["username"])); } string pwd = ""; if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"])) { pwd = Utils.Encrypt(InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["pwd"]))); } string email = ""; if (!string.IsNullOrEmpty(HttpContext.Current.Request["email"])) { email = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["email"])); } int sex = 2; if (!string.IsNullOrEmpty(HttpContext.Current.Request["sex"])) { sex = Utils.CheckInt(HttpContext.Current.Request["sex"]); } int baby = 2; if (!string.IsNullOrEmpty(HttpContext.Current.Request["baby"])) { baby = Utils.CheckInt(HttpContext.Current.Request["baby"]); } DateTime baby_date = DateTime.Now; if (!string.IsNullOrEmpty(HttpContext.Current.Request["baby_date"])) { baby_date = Convert.ToDateTime(HttpContext.Current.Request["baby_date"]); } string remark = ""; if (!string.IsNullOrEmpty(HttpContext.Current.Request["remark"])) { remark = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["remark"])); } int result = userBll.Add_User(username, pwd, email, sex, baby, baby_date, remark); 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.WritePropertyName("newid"); writer.WriteValue(result.ToString()); 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); }