private static string MergeJson( IEnumerable <string> jstrings, JsonLoadSettings loadSettings, JsonMergeSettings mergeSettings, Formatting formatting ) { if (jstrings == null || !jstrings.Any()) { return(String.Empty); } bool hasJson = false; var mergedObject = new JObject(); foreach (var jstring in jstrings) { if (!String.IsNullOrWhiteSpace(jstring)) { var overrideObject = JObject.Parse(jstring, loadSettings); mergedObject.Merge(overrideObject, mergeSettings); hasJson = true; } } if (hasJson) { return(mergedObject.ToString(formatting)); } else { return(string.Empty); } }
public static QuoteData ParseQuote(string data) { var settings = new JsonLoadSettings { }; JToken json = JToken.Parse(data, settings); QuoteData quoteData = new QuoteData(); quoteData.askPrice = (float)json["ask_price"]; quoteData.askSize = (int)json["ask_size"]; quoteData.bidPrice = (float)json["bid_price"]; quoteData.bidSize = (int)json["bid_size"]; quoteData.lastTradePrice = (float)json["last_trade_price"]; quoteData.previousClose = (float)json["previous_close"]; quoteData.adjustedPreviousClose = (float)json["adjusted_previous_close"]; quoteData.previousCloseDate = (string)json["previous_close_date"]; quoteData.symbol = (string)json["symbol"]; quoteData.tradingHalted = (bool)json["trading_halted"]; quoteData.hasTraded = (bool)json["has_traded"]; quoteData.updatedAt = (string)json["updated_at"]; if (json["last_extended_hours_trade_price"].Type != JTokenType.Null) { quoteData.lastExtendedHoursTradePrice = (float)json["last_extended_hours_trade_price"]; } return(quoteData); }
public static async Task <OutcomeC <JObject, string[]> > LoadAsync(string content) { if (content is null) { throw new JsonException("Blank content cannot be parsed to valid JSON"); } var settings = new JsonLoadSettings { CommentHandling = CommentHandling.Ignore, LineInfoHandling = LineInfoHandling.Ignore }; using (var strReader = new StringReader(content)) using (var reader = new JsonTextReader(strReader)) { try { return(await JObject.LoadAsync(reader, settings)); } catch (JsonReaderException) { return(new[] { "Content cannot be parsed to valid JSON" }); } } }
public async Task <IAsyncEnumerable <MailData> > GetMails() { await Task.CompletedTask; var settings = new JsonLoadSettings(); SourceData.Seek(0, SeekOrigin.Begin); return(new JsonAsyncEnumerable(SourceData, settings)); }
private bool ProcessCSProj(string csprojFile) { if (string.IsNullOrWhiteSpace(csprojFile) || !File.Exists(csprojFile)) { MessageBox.Show("Invalid csproj location"); return(false); } try { var projectDocument = new XmlDocument(); using (var fileStream = File.Open(csprojFile, FileMode.Open, FileAccess.ReadWrite)) { projectDocument.Load(fileStream); XmlNamespaceManager ns = new XmlNamespaceManager(projectDocument.NameTable); ns.AddNamespace("x", CSharpProjectsNamespace); var root = projectDocument.DocumentElement; var json = @"{ // ACTION REQUIRED: This file was automatically added to your project, but it // will not take effect until additional steps are taken to enable it. See the // following page for additional information: // // https://github.com/brunocunhasilva/StyleCopAnalyzers/blob/master/documentation/EnableConfiguration.md ""settings"": { ""documentationRules"": { ""companyName"": ""OutSystems"" }, ""excludedFiles"": [], ""excludedFileFilters"": [ ""\\.generated\\.cs$"", ""\\.designer\\.cs$"" ] } }"; var loadSettings = new JsonLoadSettings(); loadSettings.CommentHandling = CommentHandling.Load; loadSettings.LineInfoHandling = LineInfoHandling.Load; var stylecopSettings = JObject.Parse(json, loadSettings); if (ExcludeFromStyleCopCheckBox.Checked) { ExcludeFilesFromStyleCop(projectDocument, stylecopSettings, GetCommonsThirdPartyPath(csprojFile), ns); } // write JSON directly to a file using (StreamWriter file = File.CreateText(Directory.GetParent(csprojFile).FullName + @"\stylecop.json")) using (JsonTextWriter writer = new JsonTextWriter(file)) { stylecopSettings.WriteTo(writer); } } projectDocument.Save(csprojFile); return(true); } catch (Exception ex) { MessageBox.Show($"Exception has occurred{Environment.NewLine}{ex.Message}{Environment.NewLine}StackTrace: {ex.StackTrace}"); return(false); } }
public static JObject Deserialize(string value, JsonLoadSettings settings = null) { value = value?.Trim(); if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException(nameof(value)); } return(JObject.Parse(value, settings ?? CreateLoadSettings())); }
/// <summary> /// Creates new instance with <paramref name="formatting" /> and <paramref name="converters"/>. /// </summary> /// <param name="formatting">An indention formatting for serialization.</param> /// <param name="converters">A custom repository with converters</param> public JsonCompositeStorage(Formatting formatting, IConverterRepository converters) { Ensure.NotNull(converters, "converters"); this.formatting = formatting; this.converters = converters; loadSettings = new JsonLoadSettings(); root = new JObject(); }
private static string Convert(string path) { var schemaText = File.ReadAllText(path); var jset = new JsonLoadSettings { CommentHandling = CommentHandling.Load }; var obj = JToken.Parse(schemaText, jset); return(JTokenConverter.Convert(obj)); }
public IEnumerable <TokenError> CheckTemplate(string armTemplateJson) { var loadSettings = new JsonLoadSettings { LineInfoHandling = LineInfoHandling.Load }; var root = JObject.Parse(armTemplateJson, loadSettings); return(CheckTemplate(root)); }
/// <summary> /// Load a JObject from a string that contains JSON /// </summary> /// <param name="jObject">The jobject parameter</param> /// <param name="json">A string that contains JSON.</param> /// <param name="settings">The JsonLoadSettings used to load the JSON. If this is null, /// default load settings will be used.</param> /// <param name="dateParseHandling">The DateParseHandling settings value</param> /// <returns>A JObject populated from the string that contains JSON.</returns> public static JObject Parse(this JObject jObject, string json, JsonLoadSettings settings = null, DateParseHandling dateParseHandling = DateParseHandling.None) { using (JsonReader reader = new JsonTextReader(new StringReader(json)) { DateParseHandling = dateParseHandling }) { return(JObject.Load(reader, settings)); } }
public JsonAsyncEnumerator(StreamReader stream, JsonLoadSettings jsonLoadSettings) { _stream = stream; _jsonLoadSettings = jsonLoadSettings; _reader = new JsonTextReader(_stream); _reader.Read(); if (_reader.TokenType != JsonToken.StartArray) { throw new InvalidOperationException("The start of the json file should be an array"); } }
public JsonRequestPercolationHandler(IConfiguration configuration) { var section = configuration.GetSection(nameof(JsonRequestPercolationHandler)); jsonLoadSettings = section.Get <JsonLoadSettings>() ?? new JsonLoadSettings { CommentHandling = CommentHandling.Ignore, LineInfoHandling = LineInfoHandling.Ignore, DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Ignore }; }
private static void ProcessData(string jsonArray, List <string> headerRow, List <int> columnWidths, List <List <string> > tableData, bool useTitleCase, int headerPadding, char newLineSubstitutionChar) { var jsonLoadSettings = new JsonLoadSettings(); jsonLoadSettings.CommentHandling = CommentHandling.Ignore; JArray jArray = JArray.Parse(jsonArray, jsonLoadSettings); var ci = new CultureInfo("en-US"); // loop through each row in the array for (int i = 0; i < jArray.Count; i++) { List <string> rowData = new List <string>(); // loop through each element in the row int j = 0; foreach (JProperty jProperty in jArray[i].Children()) { if (i == 0) // if on first row, then build header { string header = ReplaceNewLines(jProperty.Name, newLineSubstitutionChar); if (useTitleCase) { header = ci.TextInfo.ToTitleCase(header); } headerRow.Add(header); columnWidths.Add(header.Length + headerPadding); } var fixedRow = ReplaceNewLines(jProperty.First.ToString(), newLineSubstitutionChar); rowData.Add(fixedRow); if (fixedRow.Length + headerPadding > columnWidths[j]) { columnWidths[j] = fixedRow.Length + headerPadding; } j++; } tableData.Add(rowData); } }
/// <summary> /// Clones a <see cref="JObject"/> preserving the line information /// </summary> /// <param name="objectToClone">The object to clone</param> /// <returns>A clone of the object with its line info</returns> internal static JObject CloneWithLineInfo(this JObject objectToClone) { var loadSettings = new JsonLoadSettings() { LineInfoHandling = LineInfoHandling.Load }; using (var objectReader = objectToClone.CreateReader()) { return(JObject.Load(objectReader, loadSettings)); } }
public static RuntimeGraph ReadRuntimeGraph(TextReader textReader) { var loadSettings = new JsonLoadSettings() { LineInfoHandling = LineInfoHandling.Ignore, CommentHandling = CommentHandling.Ignore }; using (var jsonReader = new JsonTextReader(textReader)) { return(ReadRuntimeGraph(JToken.Load(jsonReader, loadSettings))); } }
/// <summary> /// Load a JArray from a string that contains JSON /// </summary> /// <param name="jArray">The JArray object</param> /// <param name="json">A string that contains JSON.</param> /// <param name="settings">The JsonLoadSettings used to load the JSON. If this is null, /// default load settings will be used.</param> /// <param name="dateParseHandling">The DateParseHandling settings value</param> /// <param name="timeZoneHandling">The DateTimeZoneHandling settings value</param> /// <returns>A JArray populated from the string that contains JSON.</returns> public static JArray Parse(this JArray jArray, string json, JsonLoadSettings settings = null, DateParseHandling dateParseHandling = DateParseHandling.None, DateTimeZoneHandling timeZoneHandling = DateTimeZoneHandling.Unspecified) { using (JsonReader reader = new JsonTextReader(new StringReader(json)) { DateParseHandling = dateParseHandling, DateTimeZoneHandling = timeZoneHandling }) { return(JArray.Load(reader, settings)); } }
/// <summary> /// Like <see cref="JToken.Parse(string)"/>, but does not automatically deserialize strings that look like dates to <see cref="System.DateTime"/>. /// </summary> /// <remarks> /// Workaround for https://github.com/JamesNK/Newtonsoft.Json/issues/862. /// </remarks> public static JToken ParseToken(string json, JsonLoadSettings settings = null) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { reader.DateParseHandling = DateParseHandling.None; JToken t = JToken.Load(reader, settings); if (reader.Read() && reader.TokenType != JsonToken.Comment) { throw new JsonReaderException("Additional text found in JSON string after parsing content."); } return(t); } }
private void SetTransform(Stream transformStream) { this.loadSettings = new JsonLoadSettings() { CommentHandling = CommentHandling.Ignore, LineInfoHandling = LineInfoHandling.Load }; using (StreamReader transformStreamReader = new StreamReader(transformStream)) using (JsonTextReader transformReader = new JsonTextReader(transformStreamReader)) { this.transformObject = JObject.Load(transformReader, this.loadSettings); } }
/// <summary> /// Load a <see cref="JObject"/> from a byte array that contains CBOR. /// </summary> /// <param name="cbor">A <see cref="byte[]"/> that contains CBOR.</param> /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the CBOR. /// If this is <c>null</c>, default load settings will be used.</param> /// <returns>A <see cref="JObject"/> populated from the byte array that contains CBOR.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="cbor"/> is not valid CBOR. /// </exception> public static JObject Parse(byte[] cbor, JsonLoadSettings settings) { using (var reader = new CborDataReader(new MemoryStream(cbor))) { JObject o = JObject.Load(reader, settings); while (reader.Read()) { // Any content encountered here other than a comment will throw in the reader. } return(o); } }
/// <summary> /// Encode object as JSON and validate against expected JSON string. /// </summary> protected void EncodeJsonVerifyResult( BuiltInType builtInType, object data, bool useReversibleEncoding, string expected, bool topLevelIsArray, bool includeDefaults ) { string encodeInfo = $"Encoder: Json Type:{builtInType} Reversible: {useReversibleEncoding}"; TestContext.Out.WriteLine(encodeInfo); TestContext.Out.WriteLine("Data:"); TestContext.Out.WriteLine(data); TestContext.Out.WriteLine("Expected:"); if (!String.IsNullOrEmpty(expected)) { expected = $"{{\"{builtInType}\":" + expected + "}"; } else { expected = "{}"; } var formattedExpected = PrettifyAndValidateJson(expected); var encoderStream = new MemoryStream(); bool isNumber = TypeInfo.IsNumericType(builtInType) || builtInType == BuiltInType.Boolean; bool includeDefaultValues = !isNumber ? includeDefaults : false; bool includeDefaultNumbers = isNumber ? includeDefaults : true; IEncoder encoder = CreateEncoder(EncodingType.Json, Context, encoderStream, typeof(DataValue), useReversibleEncoding, topLevelIsArray, includeDefaultValues, includeDefaultNumbers); //encoder.SetMappingTables(_nameSpaceUris, _serverUris); Encode(encoder, builtInType, builtInType.ToString(), data); Dispose(encoder); var buffer = encoderStream.ToArray(); TestContext.Out.WriteLine("Result:"); var result = Encoding.UTF8.GetString(buffer); var formattedResult = PrettifyAndValidateJson(result); var jsonLoadSettings = new JsonLoadSettings() { CommentHandling = CommentHandling.Ignore, LineInfoHandling = LineInfoHandling.Ignore }; var resultParsed = JObject.Parse(result, jsonLoadSettings); var expectedParsed = JObject.Parse(expected, jsonLoadSettings); var areEqual = JToken.DeepEquals(expectedParsed, resultParsed); Assert.IsTrue(areEqual, encodeInfo); }
public static bool IsJsonArray(string jsonStr) { var load = new JsonLoadSettings { CommentHandling = CommentHandling.Ignore, DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Replace, LineInfoHandling = LineInfoHandling.Ignore }; var jtok = JToken.Parse(jsonStr, load); return(jtok is JArray jar ? true : false); }
private static void StripCommentsFromJsonFile(string fileName) { string fileContent = File.ReadAllText(fileName); var loadSettings = new JsonLoadSettings { CommentHandling = CommentHandling.Ignore }; string filteredFileContent = JArray.Parse(fileContent, loadSettings).ToString(); if (fileContent != filteredFileContent) { ProjectHelpers.CheckFileOutOfSourceControl(fileName); File.WriteAllText(fileName, filteredFileContent, Encoding.UTF8); } }
/// <summary> /// Load a JObject from a string that contains JSON /// </summary> /// <param name="jObject">The jobject parameter</param> /// <param name="json">A string that contains JSON.</param> /// <param name="settings">The JsonLoadSettings used to load the JSON. If this is null, /// default load settings will be used.</param> /// <param name="dateParseHandling">The DateParseHandling settings value</param> /// <param name="timeZoneHandling">The DateTimeZoneHandling settings value</param> /// <param name="floatParseHandling">The FloatParseHandling settings value</param> /// <returns>A JObject populated from the string that contains JSON.</returns> public static JObject Parse(this JObject jObject, string json, JsonLoadSettings settings = null, DateParseHandling dateParseHandling = DateParseHandling.None, DateTimeZoneHandling timeZoneHandling = DateTimeZoneHandling.Unspecified, FloatParseHandling floatParseHandling = FloatParseHandling.Decimal) { using (JsonReader reader = new JsonTextReader(new StringReader(json)) { DateParseHandling = dateParseHandling, DateTimeZoneHandling = timeZoneHandling, FloatParseHandling = floatParseHandling }) { return(JObject.Load(reader, settings)); } }
/// <remarks> /// Using this method instead of Json.Convert as Json.Convert can consume malformed JSON and display /// the fixed JSON. This method will allow SBE to catch an exception and then display the original /// text in the message. /// </remarks> /// <see href="https://github.com/paolosalvatori/ServiceBusExplorer/issues/425"> /// Issue:25: Bad json (duplicate keys) are ignored silently /// </see> public static T DeserializeObject <T>(string json, JsonSerializerSettings settings = null) { var jsonSerializer = JsonSerializer.CreateDefault(settings); using (var stringReader = new StringReader(json)) using (var jsonTextReader = new JsonTextReader(stringReader)) { jsonTextReader.DateParseHandling = DateParseHandling.None; var loadSettings = new JsonLoadSettings { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error }; var jToken = JToken.ReadFrom(jsonTextReader, loadSettings); return(jToken.ToObject <T>(jsonSerializer)); } }
private void JsonTest_Click(object sender, RoutedEventArgs e) { JsonLoadSettings settings = new JsonLoadSettings { CommentHandling = CommentHandling.Load, LineInfoHandling = LineInfoHandling.Load }; string JsonFromFile = File.ReadAllText("input.json"); //Parse() does not keep comments JToken objectt = JToken.Parse(JsonFromFile, settings); //output string newJson = objectt.ToString(Newtonsoft.Json.Formatting.Indented, null); //toString() will now allow for output of previous formatting File.WriteAllText("output.json", newJson); }
public static bool cq_start(IntPtr path, int authcode) { string pathtext = path.ToString(GB18030); JsonLoadSettings loadsetting = new JsonLoadSettings { CommentHandling = CommentHandling.Ignore }; JObject jObject = JObject.Parse(File.ReadAllText(pathtext.Replace(".dll", ".json")), loadsetting); DllHelper dllHelper = new DllHelper(pathtext); KeyValuePair <int, string> appinfotext = dllHelper.GetAppInfo(); AppInfo appInfo = new AppInfo(appinfotext.Value, 0, appinfotext.Key , jObject["name"].ToString(), jObject["version"].ToString(), Convert.ToInt32(jObject["version_id"].ToString()) , jObject["author"].ToString(), jObject["description"].ToString(), authcode); appInfos.Add(appInfo); return(true); }
public static AnonymizerConfigurationManager CreateFromSettingsInJson(string settingsInJson) { try { var settings = new JsonLoadSettings { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error }; var token = JToken.Parse(settingsInJson, settings); var configuration = token.ToObject <AnonymizerConfiguration>(); return(new AnonymizerConfigurationManager(configuration)); } catch (JsonException innerException) { throw new JsonException("Failed to parse configuration file", innerException); } }
public async void HandelMessage(string josn, IPEndPoint EP) { try { string ip = EP.Address.ToString(); JObject obj = new JObject(); JsonLoadSettings a = new JsonLoadSettings(); JObject MSG = JObject.Parse(josn); string command = (string)MSG.SelectToken("command"); switch (command) { case "register": register(EP); break; case "power": if (MSG.SelectToken("data").ToString().ToLower() == "on") { obj["command"] = "response"; obj["type"] = "power"; obj["data"] = "on"; db.TVs.Where(s => s.IP == ip).ToList().ForEach(x => x.status = true); } else if (MSG.SelectToken("data").ToString().ToLower() == "off") { db.TVs.Where(s => s.IP == ip).ToList().ForEach(x => x.status = false); } db.SaveChanges(); sendMessage(obj.ToString(), EP); break; case "time": tvTime(MSG, EP); break; case "get_network_device": complateRegister(MSG, EP); break; } } catch (Exception ex) { listBoxLog.Items.Add(EP.Address.ToString() + " - " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + ": main_Load Exception " + ex.Message); return; } }
/// <summary> /// Deserializes a snapshot string to an token object /// </summary> /// <param name="snapshotJson"></param> /// <returns></returns> public JToken Deserialize(string snapshotJson) { JsonLoadSettings jsonLoadSettings = JsonLoadSettings; var isValidJson = snapshotJson.IsValidJsonFormat(jsonLoadSettings); if (!isValidJson) { snapshotJson = snapshotJson .NormalizeLineEndings() .EnsureLineEnding(); snapshotJson = JsonConvert.ToString(snapshotJson); } var snapshotToken = JToken.Parse(snapshotJson, jsonLoadSettings); return(snapshotToken); }
public void Load() { string path = @"data\plugins"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } DirectoryInfo directoryInfo = new DirectoryInfo(path); int count = 0; foreach (var item in directoryInfo.GetFiles().Where(x => x.Extension == ".dll")) { if (!File.Exists(item.FullName.Replace(".dll", ".json"))) { LogHelper.WriteLine(CQLogLevel.Error, "插件载入", $"插件 {item.Name} 加载失败,原因:缺少json文件"); continue; } JsonLoadSettings loadsetting = new JsonLoadSettings { CommentHandling = CommentHandling.Ignore }; JObject json = JObject.Parse(File.ReadAllText(item.FullName.Replace(".dll", ".json")), loadsetting); int authcode = new Random().Next(); Dll dll = new Dll(); IntPtr iLib = dll.Load(item.FullName, json); if (iLib == (IntPtr)0) { LogHelper.WriteLine(CQLogLevel.Error, "插件载入", $"插件 {item.Name} 加载失败,返回句柄为空,GetLastError={Dll.GetLastError()}"); continue; } dll.DoInitialize(authcode); KeyValuePair <int, string> appInfotext = dll.GetAppInfo(); AppInfo appInfo = new AppInfo(appInfotext.Value, 0, appInfotext.Key , json["name"].ToString(), json["version"].ToString(), Convert.ToInt32(json["version_id"].ToString()) , json["author"].ToString(), json["description"].ToString(), authcode); Plugins.Add(new Plugin(iLib, appInfo, json, dll)); LogHelper.WriteLine(CQLogLevel.InfoSuccess, "插件载入", $"插件 {appInfo.Name} 加载成功"); cq_start(Marshal.StringToHGlobalAnsi(item.FullName), authcode); NotifyIconHelper.Init(json); count++; } LogHelper.WriteLine(CQLogLevel.Info, "插件载入", $"一共加载了{count}个插件"); }