Пример #1
0
        public static Object Deserialize(JSONELEMENT element)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return(null);
            }
            if (element.ValueKind == JsonValueKind.False)
            {
                return(false);
            }
            if (element.ValueKind == JsonValueKind.True)
            {
                return(true);
            }
            if (element.ValueKind == JsonValueKind.String)
            {
                return(element.GetString());
            }
            if (element.ValueKind == JsonValueKind.Number)
            {
                return(element.GetDouble());
            }
            if (element.ValueKind == JsonValueKind.Array)
            {
                return(_JsonArray.CreateFrom(element));
            }
            if (element.ValueKind == JsonValueKind.Object)
            {
                return(_JsonObject.CreateFrom(element));
            }

            throw new NotImplementedException();
        }
Пример #2
0
        public static Object DeepClone(JSONELEMENT element)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return(null);
            }
            if (element.ValueKind == JsonValueKind.False)
            {
                return(false);
            }
            if (element.ValueKind == JsonValueKind.True)
            {
                return(true);
            }
            if (element.ValueKind == JsonValueKind.String)
            {
                return(element.GetString());
            }
            if (element.ValueKind == JsonValueKind.Number)
            {
                return(element.GetRawText());                                           // use IConvertible interface when needed.
            }
            if (element.ValueKind == JsonValueKind.Array)
            {
                return(new JsonList(element));
            }
            if (element.ValueKind == JsonValueKind.Object)
            {
                return(new JsonDictionary(element));
            }

            throw new NotImplementedException();
        }
Пример #3
0
        public static object ReadValue(System.Text.Json.JsonElement elem)
        {
            if (elem.ValueKind == System.Text.Json.JsonValueKind.Object)
            {
                KeyValue[] vals = elem.EnumerateObject().ToList().SelectMany(v => DeSerializeOne(v)).ToArray();
                KeyValues  valv = new KeyValues(); valv.AddRange(vals);
                return(valv);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.Array)
            {
                // déja géré par DeSerializeOne
                //KeyValue[] vals = elem.Value.EnumerateArray().ToList().Select(v => DeSerializeOne(v)).ToArray();
                //KeyValues valv = new KeyValues(); valv.AddRange(vals);
                //retour = new KeyValue(realname, valv);
                return(null);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.Null || elem.ValueKind == System.Text.Json.JsonValueKind.Undefined)
            {
                return(null);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.False)
            {
                return(false);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.True)
            {
                return(true);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.Number)
            {
                int i = 0;
                if (elem.TryGetInt32(out i))
                {
                    return(i);
                }

                long li = 0;
                if (elem.TryGetInt64(out li))
                {
                    return(li);
                }

                double di = 0;
                if (elem.TryGetDouble(out di))
                {
                    return(di);
                }

                return(elem.GetRawText()); // !!!
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.String)
            {
                return(elem.GetString());
            }
            else
            {
                return(elem.GetRawText());
            }
        }
Пример #4
0
 public static System.Collections.Generic.IDictionary <string, string> ToDictionary(System.Text.Json.JsonElement jElement)
 {
     if (jElement.ValueKind != System.Text.Json.JsonValueKind.String)
     {
         return(null);
     }
     try
     {
         var jObject = JsonBase.FromJson <System.Text.Json.JsonElement>(jElement.GetString());
         var dict    = new System.Collections.Generic.Dictionary <string, string>();
         foreach (var item in jObject.EnumerateObject().OfType <JsonProperty>())
         {
             dict[item.Name] = item.Value.GetString();
         }
         return(dict);
     }
     catch (System.Exception ex)
     {
         // TODO Logging
     }
     return(null);
 }
Пример #5
0
        private static void AssertJsonEqualCore(JsonElement expected, JsonElement actual, Stack <object> path)
        {
            JsonValueKind valueKind = expected.ValueKind;

            AssertTrue(passCondition: valueKind == actual.ValueKind);

            switch (valueKind)
            {
            case JsonValueKind.Object:
                var expectedProperties = new List <string>();
                foreach (JsonProperty property in expected.EnumerateObject())
                {
                    expectedProperties.Add(property.Name);
                }

                var actualProperties = new List <string>();
                foreach (JsonProperty property in actual.EnumerateObject())
                {
                    actualProperties.Add(property.Name);
                }

                foreach (var property in expectedProperties.Except(actualProperties))
                {
                    AssertTrue(passCondition: false, $"Property \"{property}\" missing from actual object.");
                }

                foreach (var property in actualProperties.Except(expectedProperties))
                {
                    AssertTrue(passCondition: false, $"Actual object defines additional property \"{property}\".");
                }

                foreach (string name in expectedProperties)
                {
                    path.Push(name);
                    AssertJsonEqualCore(expected.GetProperty(name), actual.GetProperty(name), path);
                    path.Pop();
                }
                break;

            case JsonValueKind.Array:
                JsonElement.ArrayEnumerator expectedEnumerator = expected.EnumerateArray();
                JsonElement.ArrayEnumerator actualEnumerator   = actual.EnumerateArray();

                int i = 0;
                while (expectedEnumerator.MoveNext())
                {
                    AssertTrue(passCondition: actualEnumerator.MoveNext(), "Actual array contains fewer elements.");
                    path.Push(i++);
                    AssertJsonEqualCore(expectedEnumerator.Current, actualEnumerator.Current, path);
                    path.Pop();
                }

                AssertTrue(passCondition: !actualEnumerator.MoveNext(), "Actual array contains additional elements.");
                break;

            case JsonValueKind.String:
                AssertTrue(passCondition: expected.GetString() == actual.GetString());
                break;

            case JsonValueKind.Number:
            case JsonValueKind.True:
            case JsonValueKind.False:
            case JsonValueKind.Null:
                AssertTrue(passCondition: expected.GetRawText() == actual.GetRawText());
                break;

            default:
                Debug.Fail($"Unexpected JsonValueKind: JsonValueKind.{valueKind}.");
                break;
            }

            void AssertTrue(bool passCondition, string?message = null)
            {
                if (!passCondition)
                {
                    message ??= "Expected JSON does not match actual value";
                    Assert.Fail($"{message}\nExpected JSON: {expected}\n  Actual JSON: {actual}\n  in JsonPath: {BuildJsonPath(path)}");
                }
        public bool TryGet <T>(string key, out T value)
        {
            if (storage.TryGetValue(key, out object target))
            {
                if (target == null)
                {
                    value = default(T);
                    return(true);
                }

                log.Debug($"Get: Key: '{key}', RequiredType: '{typeof(T).FullName}', ActualType: '{target.GetType().FullName}'.");

                if (target is T targetValue)
                {
                    value = targetValue;
                    return(true);
                }

                JsonElement element = (JsonElement)target;

                if (typeof(T) == typeof(string))
                {
                    value = (T)(object)element.GetString();
                    return(true);
                }

                if (typeof(T) == typeof(int))
                {
                    value = (T)(object)element.GetInt32();
                    return(true);
                }

                if (typeof(T) == typeof(long))
                {
                    value = (T)(object)element.GetInt64();
                    return(true);
                }

                if (typeof(T) == typeof(decimal))
                {
                    value = (T)(object)element.GetDecimal();
                    return(true);
                }

                if (typeof(T) == typeof(double))
                {
                    value = (T)(object)element.GetDouble();
                    return(true);
                }

                if (typeof(T) == typeof(bool))
                {
                    value = (T)(object)element.GetBoolean();
                    return(true);
                }

                if (typeof(T) == typeof(IKey))
                {
                    if (element.ValueKind == JsonValueKind.Null)
                    {
                        value = default(T);
                        return(true);
                    }

                    string type = element.GetProperty("Type").GetString();
                    if (element.TryGetProperty("Guid", out JsonElement rawGuid))
                    {
                        string rawGuidValue = rawGuid.GetString();
                        if (rawGuidValue == null)
                        {
                            value = (T)(object)GuidKey.Empty(type);
                        }
                        else
                        {
                            value = (T)(object)GuidKey.Create(Guid.Parse(rawGuidValue), type);
                        }

                        return(true);
                    }
                    else if (element.TryGetProperty("Identifier", out JsonElement rawIdentifier))
                    {
                        string rawIdentifierValue = rawIdentifier.GetString();
                        if (rawIdentifierValue == null)
                        {
                            value = (T)(object)StringKey.Empty(type);
                        }
                        else
                        {
                            value = (T)(object)StringKey.Create(rawIdentifierValue, type);
                        }

                        return(true);
                    }
                }

                if (typeof(T) == typeof(Color))
                {
                    byte[] parts = element.GetString().Split(new char[] { ';' }).Select(p => Byte.Parse(p)).ToArray();
                    value = (T)(object)Color.FromArgb(parts[0], parts[1], parts[2], parts[3]);
                    log.Debug($"Get: Color: '{value}'.");
                    return(true);
                }

                if (typeof(T) == typeof(Price))
                {
                    log.Debug($"Get: Price value type: '{element.GetProperty("Value").GetType().FullName}'.");
                    decimal priceValue    = element.GetProperty("Value").GetDecimal();
                    string  priceCurrency = element.GetProperty("Currency").GetString();
                    value = (T)(object)new Price(priceValue, priceCurrency);
                    return(true);
                }

                if (typeof(T) == typeof(DateTime))
                {
                    string rawDateTime = element.GetString();
                    if (DateTime.TryParse(rawDateTime, out DateTime dateTime))
                    {
                        value = (T)(object)dateTime;
                        return(true);
                    }
                    else
                    {
                        log.Warning($"Get: Key: '{key}' not parseable to datetime from value '{rawDateTime}'.");
                        value = default(T);
                        return(false);
                    }
                }
            }

            log.Debug($"Get: Key: '{key}' NOT FOUND. Storage: '{JsonSerializer.Serialize(storage)}'.");
            value = default(T);
            return(false);
        }