public static void ReplaceData(Newtonsoft.Json.Linq.JObject dtInfo, DocX doc) { if (dtInfo != null) { foreach (var member in dtInfo.Properties().ToList()) { string value = ""; var lines = member.Value.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < lines.Length; i++) { if (i == 0) { value = lines[i]; } else { value = value + "\r" + lines[i]; } } if (member.Name == "age") { value = LabelHelper.GetAgeFromText(value); } doc.ReplaceText("{" + member.Name + "}", ReplaceHexadecimalSymbols(value)); } } }
/// <summary> /// 将返回的json转换为字典Dictionary对象 /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public Dictionary <string, object> JsonToDictionary(string jsonString) { Dictionary <string, object> ht = new Dictionary <string, object>(); object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString); //返回的结果一定是一个json对象 Newtonsoft.Json.Linq.JObject jsonObject = json as Newtonsoft.Json.Linq.JObject; if (jsonObject == null) { return(ht); } foreach (Newtonsoft.Json.Linq.JProperty jProperty in jsonObject.Properties()) { Newtonsoft.Json.Linq.JToken jToken = jProperty.Value; string value = ""; if (jToken != null) { value = jToken.ToString(); } ht.Add(jProperty.Name, value); } return(ht); }
private void SetExceptionFieldValue(Newtonsoft.Json.Linq.JObject jObject, string propertyName, object value, string fieldName, Newtonsoft.Json.Serialization.IContractResolver resolver, Newtonsoft.Json.JsonSerializer serializer) { var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(System.Exception)).GetDeclaredField(fieldName); var jsonPropertyName = resolver is Newtonsoft.Json.Serialization.DefaultContractResolver ? ((Newtonsoft.Json.Serialization.DefaultContractResolver)resolver).GetResolvedPropertyName(propertyName) : propertyName; var property = System.Linq.Enumerable.FirstOrDefault(jObject.Properties(), p => System.String.Equals(p.Name, jsonPropertyName, System.StringComparison.OrdinalIgnoreCase)); if (property != null) { var fieldValue = property.Value.ToObject(field.FieldType, serializer); field.SetValue(value, fieldValue); } }
//Perform a recursive search of the given json, and check if the values conform to our valid character set public static void PerformSearch(Newtonsoft.Json.Linq.JToken Item, ref List <string> Paths, ref bool ValueIsAlphaNumeric, string CurrentPath = "") { try//Try to convert the json object to a jarray { Newtonsoft.Json.Linq.JArray J = Newtonsoft.Json.Linq.JArray.FromObject(Item); for (int i = 0; i < J.Count; i++)//Perform a search of all items in the array { PerformSearch(J[i], ref Paths, ref ValueIsAlphaNumeric, CurrentPath + "::"); } } catch { try//Try to convert the json object to a jobject { Newtonsoft.Json.Linq.JObject J = Newtonsoft.Json.Linq.JObject.FromObject(Item); foreach (Newtonsoft.Json.Linq.JProperty Key in J.Properties()) //Look at all properties in the jobject { if (Key.Value.HasValues) //If the property has further values { if (!Paths.Contains(CurrentPath + Key.Name + ":")) //Check if we have all ready entered the current path into the path set and adds the path if we havent { Paths.Add(CurrentPath + Key.Name + ":"); } PerformSearch(Key.Value, ref Paths, ref ValueIsAlphaNumeric, CurrentPath + Key.Name + ":");//Perform search of items inside of the property } else { if (!Paths.Contains(CurrentPath + Key.Name + ":"))//Check if we have all ready entered the current path into the path set and adds the path if we havent { Paths.Add(CurrentPath + Key.Name + ":"); } if (!IsValidValueInJsonConfig(Key.Value.ToString())) //Check if the value conforms { if (!Key.Value.ToString().StartsWith("<:") && !Key.Value.ToString().StartsWith("<a:")) //ignore the non-conformity for these cases { ValueIsAlphaNumeric = false; //Indicates a value does not conform } } } } } catch //Treat the json object as a terminating value in the json { if (!IsValidValueInJsonConfig(Item.ToString())) //check if the value conforms { if (!Item.ToString().StartsWith("<:") && !Item.ToString().StartsWith("<a:")) { //if it doesnt start with discord emote indicators ValueIsAlphaNumeric = false; //Indicate that a value does not conform } } } } } }
/// <summary> /// deserializes a json string on a real object /// </summary> /// <param name="jsonString">json string</param> /// <param name="obj">the object that will be changed</param> /// <param name="onlyPropertyNamesList">this only replaces propertynames in this list and ignore others. Use null to set all properties in json</param> /// <param name="ignoreErrors">When the list is null, if a property not found, it will ignore it</param> public void JsonDeserializeOnObject(string jsonString, object obj, List <string> onlyPropertyNamesList = null, bool ignoreErrors = false) { Check.Assert(string.IsNullOrEmpty(jsonString) == false, "jsonString should not be empty"); Check.Assert(obj != null, "object should not be null"); var settings = new JsonSerializerSettings(); settings.Converters.Clear(); Newtonsoft.Json.Linq.JObject o = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(jsonString, settings); foreach (var p in o.Properties()) { try { string fieldName = p.Name; if (onlyPropertyNamesList != null) { if (onlyPropertyNamesList.Contains(fieldName) == false) { continue; // if it was not in the list just skip it } } Newtonsoft.Json.Linq.JToken jValue = p.Value; object value = null; if (jValue != null && jValue.Type != Newtonsoft.Json.Linq.JTokenType.Null) { value = jValue.ToObject(this.GetObjectFieldType(obj, fieldName)); } this.SetObjectFieldValue(fieldName, obj, value); } catch (FormatException ex) { throw new FWPropertySetValueException(p.Name, p.Value, ex); } catch (FWPropertyNotFoundException) { if (ignoreErrors == false) { throw; } } //try //{ //} //catch (FWPropertyNotFoundException) //{ // // ignoring the properties that are not available //} } }
private void LoadDocumentStructure() { try { string StructureString = System.IO.File.ReadAllText(@"E:\NASA\NASANET2017\ContaNET_Git\structure\BanorteStructure2021.json"); StructureJSON = Newtonsoft.Json.Linq.JObject.Parse(StructureString); headers = StructureJSON.Properties().Select(p => p.Name).ToArray(); if (headers != null) { declarationDictionary = new Dictionary <string, string[]>(); foreach (var Header in headers) { try { var Details = StructureJSON[Header][0]; var Fields = new string[] { }; if (Details["Type"].ToString() == "Table") { Newtonsoft.Json.Linq.JObject FieldsDetails = Newtonsoft.Json.Linq.JObject.Parse(Details["Fields"].ToString()); Fields = FieldsDetails.Properties().Select(p => p.Name).ToArray(); } else { if (Details["Fields"] != null) { Fields = Details["Fields"]?.Values <string>()?.ToArray() ?? new string[] { } } ; else { Fields = new string[] { } }; } declarationDictionary.Add(Header, Fields); } catch (Exception ex) { Console.WriteLine($"LoadDocumentStructure: {ex.Message}"); } } } } catch (Exception ex) { throw new Exception(string.Format("LoadDocumentsStructure: {0}", ex.Message)); } }
private object FillIn(Type type, Newtonsoft.Json.Linq.JObject jToken) { System.Reflection.PropertyInfo matchingProperty; var returnObject = Activator.CreateInstance(type); // TODO Revoir méthode instanciation ? Clairement ! foreach (var jProp in jToken.Properties()) { if ((matchingProperty = type.GetProperty(jProp.Name)) != null) { matchingProperty.SetValue(returnObject, DeserializeProperty(jProp.Value, matchingProperty), null); } } return(Convert.ChangeType(returnObject, type)); }
/// 将JSON输入数据格式化为指定方法的参数并调用方法执行 /// 将方法的返回结果格式化为Json字符串返回 /// </summary> /// <param name="AssemblyName"></param> /// <param name="FullClassName"></param> /// <param name="MethodName"></param> /// <param name="ParamJson"></param> /// <returns></returns> public static object ExecAPI(string AssemblyName, string FullClassName, string MethodName, string ParamJson, bool ObjectMode) { //从bin目录加载程序集dll System.Reflection.Assembly apiASM = System.Reflection.Assembly.Load(AssemblyName); //从程序集获取类型 Type apiType = apiASM.GetType(FullClassName, true, true); //创建实例 object apiObject = Activator.CreateInstance(apiType, true); //获取方法 MethodInfo mi = apiType.GetMethod(MethodName); //获取方法的参数列表 ParameterInfo[] Params = mi.GetParameters(); object[] obj = new object[Params.Length]; if (ObjectMode) { Newtonsoft.Json.Linq.JObject jsonObject = Newtonsoft.Json.Linq.JObject.Parse(ParamJson); IEnumerable <Newtonsoft.Json.Linq.JProperty> properties = jsonObject.Properties(); for (int i = 0; i < Params.Length; i++) { foreach (Newtonsoft.Json.Linq.JProperty item in properties) { if (item.Name.Trim().ToLower() == Params[i].Name.Trim().ToLower()) { Type tType = Params[i].ParameterType; //如果它是值类型,或者String if (tType.Equals(typeof(string)) || (!tType.IsInterface && !tType.IsClass)) { //改变参数类型 obj[i] = Convert.ChangeType(item.Value.ToString(), tType); } else if (tType.IsClass)//如果是类,将它的json字符串转换成对象 { obj[i] = Newtonsoft.Json.JsonConvert.DeserializeObject(item.Value.ToString(), tType); } break; } } } } else { obj[0] = ParamJson; } return(mi.Invoke(apiObject, obj)); }
public static string RandomSampleJson( string json, int?seed = null, int maxNumberOfItems = 10) { Newtonsoft.Json.Linq.JToken root = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(json); Random random = seed.HasValue ? new Random(seed.Value) : new Random(); string sampledJson; if (root.Type == Newtonsoft.Json.Linq.JTokenType.Array) { Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)root; IEnumerable <Newtonsoft.Json.Linq.JToken> tokens = array .OrderBy(x => random.Next()) .Take(random.Next(maxNumberOfItems)); Newtonsoft.Json.Linq.JArray newArray = new Newtonsoft.Json.Linq.JArray(); foreach (Newtonsoft.Json.Linq.JToken token in tokens) { newArray.Add(token); } sampledJson = newArray.ToString(); } else if (root.Type == Newtonsoft.Json.Linq.JTokenType.Object) { Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)root; IEnumerable <Newtonsoft.Json.Linq.JProperty> properties = jobject .Properties() .OrderBy(x => random.Next()) .Take(maxNumberOfItems); Newtonsoft.Json.Linq.JObject newObject = new Newtonsoft.Json.Linq.JObject(); foreach (Newtonsoft.Json.Linq.JProperty property in properties) { newObject.Add(property); } sampledJson = newObject.ToString(); } else { sampledJson = json; } return(sampledJson); }
private void RebuildList() { m_content.Controls.Clear(); if (string.IsNullOrEmpty(m_jsonResult)) { return; } try { Newtonsoft.Json.Linq.JContainer collection = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JContainer>(m_jsonResult); if (collection.Type == Newtonsoft.Json.Linq.JTokenType.Array && m_collectionType == CollectionPropertyEditorUtils.CollectionType.JsonArray) { Newtonsoft.Json.Linq.JArray arr = collection as Newtonsoft.Json.Linq.JArray; if (arr != null) { FieldContainer field; foreach (var item in arr) { field = new FieldContainer(this, m_collectionType, m_creator, item.ToString(Newtonsoft.Json.Formatting.None)); field.Width = m_content.Width; field.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; m_content.Controls.Add(field); } } } else if (collection.Type == Newtonsoft.Json.Linq.JTokenType.Object && m_collectionType == CollectionPropertyEditorUtils.CollectionType.JsonObject) { Newtonsoft.Json.Linq.JObject obj = collection as Newtonsoft.Json.Linq.JObject; if (obj != null) { FieldContainer field; foreach (var item in obj.Properties()) { field = new FieldContainer(this, m_collectionType, m_creator, item.Value.ToString(Newtonsoft.Json.Formatting.None), item.Name); field.Width = m_content.Width; field.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; m_content.Controls.Add(field); } } } } catch { } RepositionList(); }
/* * * 1.正确时返回结果{"sendno":"123456","msg_id":"1799597405"} * * 或者 {"sendno":"0","msg_id":"351403900"} * * 2.入参json完全正确,但找不到要到达的设备。错误时:返回 * * {"msg_id": 3125719446, "error": {"message": "cannot find user by this audience", "code": 1011}} * * 3.传入空字符串 或者 非json格式,或者没有必须的选项:{"error": {"message": "Missing parameter", "code": 1002}} * * 传入的键(键区分大小写)、值不符合要求 {"error": {"message": "Audience value must be JSON Array format!", "code": 1003}} * */ /// <summary> /// 将返回的json转换为Hashtable对象 /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public Hashtable JsonToHashtable(string jsonString) { /* * * 正确时返回结果{"sendno":"123456","msg_id":"1799597405"} * * {"sendno":"0","msg_id":"351403900"} * * 入参json完全正确,但找不到要到达的设备。错误时:返回 {"msg_id": 3125719446, "error": {"message": "cannot find user by this audience", "code": 1011}} * * 传入空字符串 或者 非json格式,或者没有必须的选项:{"error": {"message": "Missing parameter", "code": 1002}} * * 传入的键值不符合要求 {"error": {"message": "Audience value must be JSON Array format!", "code": 1003}} 键区分大小写 * */ Hashtable ht = new Hashtable(); object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString); //返回的结果一定是一个json对象 Newtonsoft.Json.Linq.JObject jsonObject = json as Newtonsoft.Json.Linq.JObject; if (jsonObject == null) { return(ht); } foreach (Newtonsoft.Json.Linq.JProperty jProperty in jsonObject.Properties()) { Newtonsoft.Json.Linq.JToken jToken = jProperty.Value; string value = ""; if (jToken != null) { value = jToken.ToString(); } ht.Add(jProperty.Name, value); } return(ht); }
private void SaveTableToFile(string filename) { Table tbl = new Table(); string jsonData; using (StreamReader sr = new StreamReader("wwwroot\\" + filename)) { jsonData = sr.ReadToEnd(); } Newtonsoft.Json.Linq.JObject JsonObj = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(jsonData); var proep = JsonObj.Properties(); foreach (Newtonsoft.Json.Linq.JProperty p in proep) { if (!(p.Name.Equals("acronym") | p.Name.Equals("content"))) { tbl.TableProperties.Add(p.Name, p.Value.ToString()); } else if (p.Name.Equals("acronym")) { tbl.ID = p.Value.ToString(); } else if (p.Name.Equals("content")) { Element e; Newtonsoft.Json.Linq.JArray v = (Newtonsoft.Json.Linq.JArray)p.Value; foreach (var attributex in v) { e = new Element(); foreach (Newtonsoft.Json.Linq.JProperty t in attributex) { if (t.Name.Equals("identifier")) { e.ID = t.Value.ToString(); } e.Values.Add(t.Name, t.Value.ToString()); } tbl.TableElements.Add(e.ID, e); } } } js.Add(tbl); js.SaveChanges(); }
private static Dictionary <string, object> Flatten(Newtonsoft.Json.Linq.JObject Dictionary) { var result = new Dictionary <string, object>(); foreach (var pair in Dictionary.Properties()) { var flat = Flatten(pair.Value); if (flat is Dictionary <string, object> ) { foreach (var item in (Dictionary <string, object>)flat) { result[item.Key] = item.Value; } } else { result[pair.Name] = flat; } } return(result); }
/// <summary> /// InitializeExecutors method adds listeners in list listener. /// </summary> /// <param name="loggerConfig"> Json.Linq.JObject with a minimum logging level for the logger and a list of listener objects. </param> private void InitializeExecutors(Newtonsoft.Json.Linq.JObject loggerConfig) { Assembly assembly = null; Type [] classesAssebmly = null; IListener executor = null; LogLevel extcutorLogLevel = 0; Type executorClass = null; foreach (var objExecutor in loggerConfig.Properties()) { if (objExecutor.Name != "MinLogLevel") { assembly = Assembly.Load(objExecutor.Name); classesAssebmly = assembly.GetTypes(); executorClass = assembly.GetType(classesAssebmly[0].FullName); executor = (IListener)Activator.CreateInstance(executorClass, (string)loggerConfig[objExecutor.Name]["Source"]); executor.Loglevel = ParseEnum <LogLevel>((string)loggerConfig[objExecutor.Name]["LogLevel"]); ExecutorLogger.Add(executor); } } }
public async Task <IActionResult> ConnectCallback(string code) { string url = $"https://oauth.vk.com/access_token?" + $"client_id={_configuration.GetValue<long>("VkApplicationId")}" + $"&client_secret={_configuration.GetValue<string>("VkApplicationPassword")}" + $"&redirect_uri={$"{_configuration.GetValue<string>("SiteUrl")}/Groups/ConnectCallback"}" + $"&code={code}"; string result = null; using (var client = new HttpClient()) { var response = await client.PostAsync(url, null); result = await response.Content.ReadAsStringAsync(); Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(result); //TODO: Добавить проверку на null у token var token = obj.Properties().FirstOrDefault(x => x.Name.StartsWith("access_token_")); var idGroup = long.Parse(token.Name.Split('_').Last()); string tokenValue = token.Value.ToString(); var group = await _context.Groups.Where(x => x.IdVk == idGroup).FirstOrDefaultAsync(); if (group == null) { group = new Groups() { IdVk = idGroup }; await _context.Groups.AddAsync(group); } group.AccessToken = tokenValue; using (var vkGroupApi = new VkNet.VkApi()) { await vkGroupApi.AuthorizeAsync(new VkNet.Model.ApiAuthParams() { AccessToken = tokenValue, Settings = VkNet.Enums.Filters.Settings.Groups }); group.CallbackConfirmationCode = await vkGroupApi.Groups.GetCallbackConfirmationCodeAsync((ulong)idGroup); var groups = await vkGroupApi.Groups.GetByIdAsync(null, idGroup.ToString(), VkNet.Enums.Filters.GroupsFields.Description); var groupInfo = groups.FirstOrDefault(); group.Name = groupInfo.Name; group.Photo = groupInfo.Photo50.ToString(); } await _context.SaveChangesAsync(); var idUser = _userHelperService.GetUserId(User); var groupAdmin = await _context.GroupAdmins.Where(x => x.IdUser == idUser && x.IdGroup == idGroup).FirstOrDefaultAsync(); if (groupAdmin == null) { groupAdmin = new GroupAdmins() { IdGroup = idGroup, IdUser = idUser, DtConnect = DateTime.UtcNow }; await _context.GroupAdmins.AddAsync(groupAdmin); } else { groupAdmin.DtConnect = DateTime.UtcNow; } await _context.SaveChangesAsync(); url = $"https://api.vk.com/method/groups.getCallbackServers?" + $"access_token={tokenValue}" + $"&group_id={idGroup}" + $"&v={AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion}"; response = await client.PostAsync(url, null); result = await response.Content.ReadAsStringAsync(); var callbackServers = new VkResponse(result).ToVkCollectionOf <VkNet.Model.CallbackServerItem>(x => x); long idServer = -1; var callbackServerUrl = _configuration.GetValue <string>("CallbackServerUrl"); var callbackServerInfo = callbackServers.FirstOrDefault(x => x.Url == callbackServerUrl); if (callbackServerInfo == null) { url = $"https://api.vk.com/method/groups.addCallbackServer?" + $"access_token={tokenValue}" + $"&group_id={idGroup}" + $"&url={_configuration.GetValue<string>("SiteUrl")}{callbackServerUrl}" + $"&title={_configuration.GetValue<string>("CallbackServerName")}" + $"&v={AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion}"; response = await client.PostAsync(url, null); result = await response.Content.ReadAsStringAsync(); var json = Newtonsoft.Json.Linq.JObject.Parse(result); idServer = new VkResponse(json[propertyName: "response"]) { RawJson = result }[key: "server_id"]; } else { idServer = callbackServerInfo.Id; } var callbackProperties = new VkNet.Model.CallbackSettings(); foreach (var property in callbackProperties.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) { property.SetValue(callbackProperties, true); } var parameters = VkNet.Model.RequestParams.CallbackServerParams.ToVkParameters(new VkNet.Model.RequestParams.CallbackServerParams() { GroupId = (ulong)idGroup, ServerId = idServer, CallbackSettings = callbackProperties }); parameters.Add("access_token", tokenValue); parameters.Add("v", AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion); url = "https://api.vk.com/method/groups.setCallbackSettings"; HttpContent content = new FormUrlEncodedContent(parameters); response = await client.PostAsync(url, content); result = await response.Content.ReadAsStringAsync(); } return(RedirectToAction(nameof(IndexConnected), "Groups")); }
private void FormatTextTable(ref string Text, int StartIndex, Newtonsoft.Json.Linq.JToken groupStructure) { try { Newtonsoft.Json.Linq.JObject StructureJSONTable = Newtonsoft.Json.Linq.JObject.Parse(groupStructure["Fields"].ToString()); string[] FieldsTable = StructureJSONTable.Properties().Select(p => p.Name).ToArray(); foreach (string Field in FieldsTable) { Newtonsoft.Json.Linq.JObject FieldProperties = Newtonsoft.Json.Linq.JObject.Parse(StructureJSONTable[Field].ToString()); //buscamos los registros de las tablas que inicien con la expresión indicada Regex PatternRegex = new Regex(FieldProperties["PatternStart"].ToString(), RegexOptions.Multiline); MatchCollection coincidencias = PatternRegex.Matches(Text, StartIndex); if (coincidencias != null && coincidencias.Count > 0) { //1.- IDENTIFICAR LOS REGISTROS //agregamos en texto REGISTRO para indicar que es una fila de la tabla var startAt = 0; foreach (Match item in coincidencias) { Text = PatternRegex.Replace(Text, $"{Field}={item.Value}", 1, item.Index + startAt); startAt = item.Length; } //2.- BUSCAMOS LAS FILAS MARCADAS Y LAS VOLVEMOS A DIVIDIR Regex PatternRegex_Split = new Regex($"{Field}=", RegexOptions.Multiline | RegexOptions.Compiled); string[] rows_split = PatternRegex_Split.Split(Text); //3.- MARCAMOS NUEVAMENTE LOS REGISTRO Y ELIMINAMOS LOS SALTOS DE LINEA PARA AGRUPAR CADA REGISTRO for (int i = 0; i < rows_split.Length; i++) { //verficicamos si cada fila inicia con la palabra llave indicando que es una fila PatternRegex = new Regex(FieldProperties["PatternStart"].ToString(), RegexOptions.Multiline); if (PatternRegex.IsMatch(rows_split[i])) { //reemplazamos los saltos de linea con un pipe para poder tener una referencia donde termina la fila var line = rows_split[i].ToString().Replace("\r", "|").Replace("\n", ""); //buscamos donde termina la fila var pattern2 = new Regex(FieldProperties["PatternEnd"].ToString()); Match rtes = pattern2.Match(line); if (rtes.Success && rtes.Index > 0) { //Reemplazamos el pipe con un espacio en blanco y recortamos la fila hasta donde termina la coincidencia con el regex rows_split[i] = $"{Field}={line.Substring(0, rtes.Index + rtes.Length).Replace("|", " ")}"; //si es la ultima posición reemplazamos el pipe y concatenamos el texto que no pertenece a la fila para que no se pierda el texto if (i + 1 == rows_split.Length) { if (line.Length > rtes.Index + rtes.Length) { rows_split[i] += "\n" + line.Substring(rtes.Index + rtes.Length, line.Length - (rtes.Index + rtes.Length)).Replace("|", ""); } } } } } //UNIMOS EL CONTENIDO Text = string.Join("\n", rows_split); } } } catch { } }
private static void MergeJsonObjects(Newtonsoft.Json.Linq.JObject self, Newtonsoft.Json.Linq.JObject other) { foreach (var p in other.Properties()) { var sp = self.Property(p.Name); if (sp == null) { self.Add(p); } else { switch (p.Type) { // Primitives override case Newtonsoft.Json.Linq.JTokenType.Boolean: case Newtonsoft.Json.Linq.JTokenType.Bytes: case Newtonsoft.Json.Linq.JTokenType.Comment: case Newtonsoft.Json.Linq.JTokenType.Constructor: case Newtonsoft.Json.Linq.JTokenType.Date: case Newtonsoft.Json.Linq.JTokenType.Float: case Newtonsoft.Json.Linq.JTokenType.Guid: case Newtonsoft.Json.Linq.JTokenType.Integer: case Newtonsoft.Json.Linq.JTokenType.String: case Newtonsoft.Json.Linq.JTokenType.TimeSpan: case Newtonsoft.Json.Linq.JTokenType.Uri: case Newtonsoft.Json.Linq.JTokenType.None: case Newtonsoft.Json.Linq.JTokenType.Null: case Newtonsoft.Json.Linq.JTokenType.Undefined: self.Replace(p); break; // Arrays merge case Newtonsoft.Json.Linq.JTokenType.Array: if (sp.Type == Newtonsoft.Json.Linq.JTokenType.Array) { sp.Value = new Newtonsoft.Json.Linq.JArray(((Newtonsoft.Json.Linq.JArray)sp.Value).Union((Newtonsoft.Json.Linq.JArray)p.Value)); } else { var a = new Newtonsoft.Json.Linq.JArray(sp.Value); sp.Value = new Newtonsoft.Json.Linq.JArray(a.Union((Newtonsoft.Json.Linq.JArray)p.Value)); } break; // Objects merge case Newtonsoft.Json.Linq.JTokenType.Object: if (sp.Type == Newtonsoft.Json.Linq.JTokenType.Object) { MergeJsonObjects((Newtonsoft.Json.Linq.JObject)sp.Value, (Newtonsoft.Json.Linq.JObject)p.Value); } else { sp.Value = p.Value; } break; // Ignore other stuff default: break; } } } }
void parseJson(Newtonsoft.Json.Linq.JObject jsonObj, List <StringBuilder> classList, string className) { var jsonProperty = jsonObj.Properties(); StringBuilder resultStr = new StringBuilder(); classList.Add(resultStr); resultStr.AppendLine("class " + className + "{"); foreach (var pro in jsonProperty) { string name = pro.Name; var value = pro.Value as Newtonsoft.Json.Linq.JValue; resultStr.Append("public "); if (pro.Value == null) { resultStr.Append("object "); } else if (pro.Value.Type == Newtonsoft.Json.Linq.JTokenType.Object) { string myName = name[0].ToString().ToUpper() + name.Substring(1); resultStr.Append(className + "_" + myName + " "); parseJson((Newtonsoft.Json.Linq.JObject)pro.Value, classList, className + "_" + myName); } else if (pro.Value.Type == Newtonsoft.Json.Linq.JTokenType.Array) { string otherString = "[]"; Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)pro.Value; _check: if (array.Count > 0 && array[0].Type == Newtonsoft.Json.Linq.JTokenType.Object) { string myName = name[0].ToString().ToUpper() + name.Substring(1); resultStr.Append(className + "_" + myName + otherString + " "); parseJson((Newtonsoft.Json.Linq.JObject)array[0], classList, className + "_" + myName); } else if (array.Count > 0 && array[0].Type == Newtonsoft.Json.Linq.JTokenType.Array) { array = (Newtonsoft.Json.Linq.JArray)array[0]; otherString += "[]"; goto _check; } else { resultStr.Append("object "); } } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.String) { resultStr.Append("string "); } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Integer) { resultStr.Append("int? "); } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Boolean) { resultStr.Append("bool "); } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Bytes) { resultStr.Append("byte[] "); } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Date) { resultStr.Append("DateTime? "); } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Float) { resultStr.Append("double? "); } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Guid) { resultStr.Append("Guid "); } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.TimeSpan) { resultStr.Append("TimeSpan? "); } else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Object) { parseJson((Newtonsoft.Json.Linq.JObject)pro.Value, classList, className + "_" + name); } else { resultStr.Append("object "); } resultStr.Append(name); resultStr.AppendLine("{get;set;}"); resultStr.AppendLine(""); } resultStr.AppendLine("}"); }
} // End Sub WriteJson public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { NodeState RetVal = NodeState.none; Newtonsoft.Json.Linq.JObject jsonObject = Newtonsoft.Json.Linq.JObject.Load(reader); System.Collections.Generic.IEnumerable <Newtonsoft.Json.Linq.JProperty> properties = jsonObject.Properties(); //.ToList(); foreach (Newtonsoft.Json.Linq.JProperty CurProp in properties) { // Console.WriteLine(CurProp.Name); // Console.WriteLine(CurProp.Value); NodeState CurVal = (NodeState)Enum.Parse(typeof(NodeState), CurProp.Name); RetVal = RetVal | CurVal; } // Next CurProp return(RetVal); } // End Function ReadJson
private static List <string> GetFieldNames(dynamic input) { List <string> fieldNames = new List <string>(); try { // Deserialize the input json string to an object input = Newtonsoft.Json.JsonConvert.DeserializeObject(input); // Json Object could either contain an array or an object or just values // For the field names, navigate to the root or the first element input = input.Root ?? input.First ?? input; if (input != null) { //// Get to the first element in the array bool isArray = true; while (isArray) { input = input.First ?? input; if (input.GetType() == typeof(Newtonsoft.Json.Linq.JObject) || input.GetType() == typeof(Newtonsoft.Json.Linq.JValue) || input == null) { isArray = false; } } // check if the object is of type JObject. // If yes, read the properties of that JObject if (input.GetType() == typeof(Newtonsoft.Json.Linq.JObject)) { // Create JObject from object Newtonsoft.Json.Linq.JObject inputJson = Newtonsoft.Json.Linq.JObject.FromObject(input); // Read Properties var properties = inputJson.Properties(); // Loop through all the properties of that JObject foreach (var property in properties) { // Check if there are any sub-fields (nested) // i.e. the value of any field is another JObject or another JArray if (property.Value.GetType() == typeof(Newtonsoft.Json.Linq.JObject) || property.Value.GetType() == typeof(Newtonsoft.Json.Linq.JArray)) { // If yes, enter the recursive loop to extract sub-field names var subFields = GetFieldNames(property.Value.ToString()); if (subFields != null && subFields.Count() > 0) { // join sub-field names with field name //(e.g. Field1.SubField1, Field1.SubField2, etc.) //fieldNames.AddRange( // subFields // .Select(n => // string.IsNullOrEmpty(n) ? property.Name : // string.Format("{0}.{1}", property.Name, n))); fieldNames.AddRange( subFields .Select(n => string.IsNullOrEmpty(n) ? property.Name : string.Format("{0}", n))); } } else { // If there are no sub-fields, the property name is the field name fieldNames.Add(property.Name); } } } else if (input.GetType() == typeof(Newtonsoft.Json.Linq.JValue)) { // for direct values, there is no field name fieldNames.Add(string.Empty); } } } catch { throw; } return(fieldNames); }