Example #1
0
        public void PopulateFromSerializationText(string json, JsonSerializationSettings?jss = null)
        {
            if (jss == null)
            {
                jss = new JsonSerializationSettings();
            }

            // Must be an array...
            if (jss.SerializationType == SerializationType.Array)
            {
                if (!Regex.IsMatch(json, @"^\s*\[") || !Regex.IsMatch(json, @"\]\s*$"))
                {
                    throw new CEFInvalidStateException(InvalidStateType.Serialization, "JSON provided is not an array (must be to deserialize a service scope).");
                }
            }

            var il = CEF.CurrentPCTService()?.GetItemsFromSerializationText <T>(json, jss);

            if (il != null)
            {
                foreach (var i in il)
                {
                    this.Add(i);
                }
            }
        }
        private static async Task WriteExceptionAsync(HttpContext context, object responseContent)
        {
            var response = context.Response;

            response.ContentType = "text/json";
            response.StatusCode  = 500;
            await response.WriteAsync(
                JsonConvert.SerializeObject(responseContent, JsonSerializationSettings.Default())
                ).ConfigureAwait(false);
        }
Example #3
0
 public JsonDataSerializer(IOptions <JsonSerializationSettings> options)
 {
     _settings   = options.Value;
     _serializer = new JsonSerializer
     {
         ReferenceLoopHandling      = ReferenceLoopHandling.Ignore,
         Formatting                 = Formatting.None,
         PreserveReferencesHandling = _settings.PreserveReferences ? PreserveReferencesHandling.All : PreserveReferencesHandling.None
     };
 }
 public static object Deserialize(string json, Type type, JsonSerializationSettings settings = JsonSerializationSettings.Default)
 {
     try
     {
         return(JsonConvert.DeserializeObject(json, type, BuildSettings(settings)));
     }
     catch (Exception exc)
     {
         Logger.Error("Cannot deserialize the Json", exc);
         throw;
     }
 }
 public static string Serialize(object obj, Type type, JsonSerializationSettings settings = JsonSerializationSettings.Default)
 {
     try
     {
         return(JsonConvert.SerializeObject(obj, Formatting.Indented, BuildSettings(settings)));
     }
     catch (Exception exc)
     {
         Logger.Error("Cannot serialize the Json", exc);
         throw;
     }
 }
        private static JsonSerializerSettings BuildSettings(JsonSerializationSettings settings = JsonSerializationSettings.Default)
        {
            if (settings == JsonSerializationSettings.Default)
            {
                return(SerializerSettings);
            }

            if ((settings & JsonSerializationSettings.NoEmbeddedTypes) != 0)
            {
                return(SerializerSettingsWithNoTypeHandling);
            }

            return(null);
        }
Example #7
0
        public IEnumerable <T> GetItemsFromSerializationText <T>(string json, JsonSerializationSettings settings) where T : class, new()
        {
            if (settings == null)
            {
                settings = new JsonSerializationSettings();
            }

            switch (settings.SerializationType)
            {
            case SerializationType.Array:
            {
                var setArray = JArray.Parse(json);

                foreach (var i in setArray.Children())
                {
                    if (i.Type == JTokenType.Object)
                    {
                        yield return(CEF.Deserialize <T>(i.ToString()));
                    }
                }

                break;
            }

            case SerializationType.ObjectWithSchemaType1AndRows:
            {
                // Read schema
                Dictionary <string, Type> schema = new Dictionary <string, Type>();

                var root = JObject.Parse(json);

                // Read schema
                foreach (var propInfo in root.GetValue(settings.SchemaName).ToArray())
                {
                    if (propInfo is JObject jo)
                    {
                        if (jo.Count < 2 || jo.Count > 3)
                        {
                            throw new CEFInvalidOperationException("Invalid JSON format.");
                        }

                        JProperty pn = (from a in jo.Children() let b = a as JProperty where b != null && b.Name.Equals(settings.SchemaFieldNameName) select b).FirstOrDefault();
                        JProperty pt = (from a in jo.Children() let b = a as JProperty where b != null && b.Name.Equals(settings.SchemaFieldTypeName) select b).FirstOrDefault();
                        JProperty pr = (from a in jo.Children() let b = a as JProperty where b != null && b.Name.Equals(settings.SchemaFieldRequiredName) select b).FirstOrDefault();

                        if (pn == null || pt == null)
                        {
                            throw new CEFInvalidOperationException("Invalid JSON format.");
                        }

                        var t     = settings.GetDataType(pt.Value.ToString());
                        var torig = t;

                        // Assume that any property might be omitted/missing which means everything should be considered nullable
                        if (t.IsValueType && !(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable <>)))
                        {
                            t = typeof(Nullable <>).MakeGenericType(t);
                        }

                        var name = pn.Value.ToString();
                        schema[name] = t;

                        // If is required, we add a validation for this
                        if (pr != null && bool.TryParse(pr.Value.ToString(), out bool prv) && prv)
                        {
                            ValidationService.RegisterRequired <T>(torig, name);
                        }
                    }
                }

                // Read objects, using the schema as the "basis" where missing/omitted properties are still carried through
                foreach (var itemInfo in root.GetValue(settings.DataRootName).ToArray())
                {
                    var obj = CEF.Deserialize <T>(itemInfo.ToString());
                    var iw  = obj.AsInfraWrapped();

                    // We need to apply property type settings after-the-fact
                    var allProp = iw.GetAllValues();

                    foreach (var propInfo in schema)
                    {
                        var existingInfo = (from a in allProp where a.Key == propInfo.Key select(propInfo.Value, a.Value));

                        if (existingInfo.Any())
                        {
                            iw.SetValue(propInfo.Key, existingInfo.First().Item2, existingInfo.First().Item1);
                        }
                        else
                        {
                            iw.SetValue(propInfo.Key, null, propInfo.Value);
                        }
                    }

                    yield return(obj);
                }

                break;
            }
            }
        }
 public static string Serialize <T>(T obj, JsonSerializationSettings settings = JsonSerializationSettings.Default)
 {
     return(Serialize(obj, obj.GetType(), settings));
 }