using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Globalization; using System.Text; using System.Threading.Tasks; namespace Neo.LegitimateLicences.Desktop.Helpers { public class JsonHelper { #region GetValidString public static string GetValidString(JValue obj) { return obj.ToString(); //if (obj.Value != null) //{ // return obj.ToString(); //} //else //{ // return "-"; //} } #endregion #region GetValidLong public static long? GetValidLong(JValue obj) { if (obj.Value != null) { return Convert.ToInt64(obj.ToString()); } else { return null; } } #endregion #region GetValidInt public static int? GetValidInt(JValue obj) { if (obj.Value != null) { return Convert.ToInt32(obj.ToString()); } else { return null; } } #endregion #region GetValidShort public static short? GetValidShort(JValue obj) { if (obj.Value != null) { return Convert.ToInt16(obj.ToString()); } else { return null; } } #endregion #region GetValidDate public static DateTime? GetValidDate(JValue obj) { if (obj.Value != null) { return Convert.ToDateTime(obj.ToString()); } else { return null; } } #endregion #region GetValidDouble public static double GetValidDouble(JValue obj) { if (obj == null || obj.Value == null) { return 0d; } var s = obj.ToString().Trim(); if (string.IsNullOrWhiteSpace(s)) return 0d; // Remove spaces s = s.Replace(" ", ""); // Normalize decimal/thousand separators: handle "627,66" or "627,66" with thousands if (s.IndexOf(',') != -1 && s.IndexOf('.') == -1) { s = s.Replace(',', '.'); } else { var commaCount = s.Count(c => c == ','); var dotCount = s.Count(c => c == '.'); if (commaCount + dotCount > 1) { var lastSep = Math.Max(s.LastIndexOf(','), s.LastIndexOf('.')); var intPart = new string(s.Substring(0, lastSep).Where(ch => ch != ',' && ch != '.').ToArray()); var decPart = s.Substring(lastSep + 1); s = intPart + "." + decPart; } } if (double.TryParse(s, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var d)) { return d; } return 0d; } #endregion } }