コード例 #1
0
        public static string Serialize(IEnumerable <object> entities, IEnumerable <string> bodies, bool doNotSerializeBody = false)
        {
            var entityEnumerable = entities as object[] ?? entities.ToArray();
            var bodyEnumerable   = bodies as string[] ?? bodies.ToArray();

            if (entityEnumerable.Length == 0 || bodyEnumerable.Length == 0 ||
                entityEnumerable.Length != bodyEnumerable.Length)
            {
                return(null);
            }
            var type = entityEnumerable[0].GetType();

            GetProperties(type);
            if (!propertyCache.ContainsKey(type.FullName))
            {
                return(null);
            }
            var propertyDictionary = propertyCache[type.FullName];
            var entityList         = new List <SortedDictionary <string, object> >(entityEnumerable.Length);

            for (var i = 0; i < entityEnumerable.Length; i++)
            {
                var entityDictionary = new SortedDictionary <string, object>();
                if (!doNotSerializeBody && JsonSerializerHelper.IsJson(bodyEnumerable[i]))
                {
                    try
                    {
                        entityDictionary.Add("body", JObject.Parse(bodyEnumerable[i]));
                    }
                    catch (Exception)
                    {
                        try
                        {
                            entityDictionary.Add("body", JArray.Parse(bodyEnumerable[i]));
                        }
                        catch (Exception)
                        {
                            entityDictionary.Add("body", bodyEnumerable[i]);
                        }
                    }
                }
                else
                {
                    entityDictionary.Add("body", bodyEnumerable[i]);
                }
                foreach (var keyValuePair in propertyDictionary)
                {
                    var camelCase = string.Format("{0}{1}",
                                                  keyValuePair.Key.Substring(0, 1).ToLower(CultureInfo.InvariantCulture),
                                                  keyValuePair.Key.Substring(1, keyValuePair.Key.Length - 1));
                    entityDictionary.Add(camelCase, null);
                    try
                    {
                        var value = keyValuePair.Value.GetValue(entityEnumerable[i], null);
                        entityDictionary[camelCase] = value;
                    }
                    // ReSharper disable once EmptyGeneralCatchClause
                    catch (Exception)
                    {
                    }
                }
                entityList.Add(entityDictionary);
            }
            return(JsonSerializerHelper.Serialize(entityList.ToArray(), Formatting.Indented));
        }